⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 chapter16.html

📁 java 是一个很好的网络开发环境。由于它是通过解释的方法
💻 HTML
📖 第 1 页 / 共 5 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<!--
This document was converted from RTF source: 
By rtftohtml 4.19
See http://www.sunpack.com/RTF
Filename:Tjava14.rtf
Application Directory:c:\TOOLS\RTF2HTML\
Subject:
Author:Bruce Eckel
Operator:Bruce Eckel
Document Comments:
Version Comments:
Comments:
Keywords:
Translation Date:02/04/2000
Translation Time:23:26:14
Translation Platform:Win32
Number of Output files:27
This File:Chapter16.html
SplitDepth=1
SkipNavPanel=1
SkipLeadingToc=1
SkipTrailingToc=1
GenContents=1
GenFrames=1
GenIndex=1
-->
<HEAD lang="en"><META http-equiv="Content-Type" content="text/html">
<TITLE>16: Design patterns</TITLE>
</HEAD>

<BODY  BGCOLOR="#FFFFFF"><DIV ALIGN="CENTER">
  <a href="http://www.MindView.net">
  <img src="mindview-head.gif" alt="MindView Inc." BORDER = "0"></a>
  <CENTER>
    <FONT FACE="Verdana" size = "-1">
    [ <a href="README-HTML.txt">Viewing Hints</a> ]
    [ <a href="http://www.mindview.net/TIJ2/index.html">2nd Edition</a> ]
    [ <a href="http://www.mindview.net/MailingList.html">Free Newsletter</a> ] <br>
    [ <a href="http://www.mindview.net/Training.html">Seminars</a> ]
    [ <a href="http://www.mindview.net/javaCD2.html">Seminars on CD ROM</a> ]
    [ <a href="http://www.mindview.net/CPPServices/#ConsultingServices">Consulting</a> ]
    </FONT>
  <H2><FONT FACE="Verdana">
  Thinking in Java, 1st edition</FONT></H2>
  <H3><FONT FACE="Verdana">&copy;1998 by Bruce Eckel</FONT></H3>
  
    <FONT FACE="Verdana" size = "-1">
     [ <a href="Chapter15.html">Previous Chapter</a> ] 
    [ <a href="SimpleContents.html">Short TOC</a> ] 
    [ <a href="Contents.html">Table of Contents</a> ] 
    [ <a href="DocIndex.html">Index</a> ]
     [ <a href="Chapter17.html">Next Chapter</a> ] 
    </FONT>
    
  </CENTER>
  </P></DIV><A NAME="Chapter_13"></A><A NAME="_Toc375545412"></A><A NAME="_Toc407441460"></A><A NAME="_Toc408018793"></A><A NAME="Heading550"></A><FONT FACE = "Verdana"><H1 ALIGN="LEFT">
16: Design patterns</H1></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Verdana" SIZE=4>This chapter introduces
the important and yet non-traditional &#8220;patterns&#8221; approach to program
design. </FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Probably the most important step
forward in object-oriented design is the &#8220;design patterns&#8221; movement,
chronicled in <A NAME="Index2900"></A><A NAME="Index2901"></A><I>Design
Patterns</I>, by Gamma, Helm, Johnson &amp; Vlissides (Addison-Wesley
1995).</FONT><A NAME="fnB66" HREF="#fn66">[66]</A><FONT FACE="Georgia">
That book shows 23 different solutions to particular classes of problems. In
this chapter, the basic concepts of design patterns will be introduced along
with several examples. This should whet your appetite to read <I>Design
Patterns</I> (a source of what has now become an essential, almost mandatory,
vocabulary for OOP programmers).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The latter part of this chapter
contains an example of the design evolution process, starting with an initial
solution and moving through the logic and process of evolving the solution to
more appropriate designs. The program shown (a trash sorting simulation) has
evolved over time, and you can look at that evolution as a prototype for the way
your own design can start as an adequate solution to a particular problem and
evolve into a flexible approach to a class of
problems.</FONT><A NAME="_Toc408018794"></A><BR></P></DIV>
<A NAME="Heading551"></A><FONT FACE = "Verdana"><H2 ALIGN="LEFT">
The pattern concept</H2></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Initially, you can think of a
pattern as an especially clever and insightful way of solving a particular class
of problems. That is, it looks like a lot of people have worked out all the
angles of a problem and have come up with the most general, flexible solution
for it. The problem could be one you have seen and solved before, but your
solution probably didn&#8217;t have the kind of completeness you&#8217;ll see
embodied in a pattern.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Although they&#8217;re called
&#8220;design patterns,&#8221; they really aren&#8217;t tied to the realm of
design. A pattern seems to stand apart from the traditional way of thinking
about analysis, design, and implementation. Instead, a pattern embodies a
complete idea within a program, and thus it can sometimes appear at the analysis
phase or high-level design phase. This is interesting because a pattern has a
direct implementation in code and so you might not expect it to show up before
low-level design or implementation (and in fact you might not realize that you
need a particular pattern until you get to those phases).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The basic concept of a pattern can
also be seen as the basic concept of program design: adding a layer of
<A NAME="Index2902"></A><A NAME="Index2903"></A>abstraction. Whenever you
abstract something you&#8217;re isolating particular details, and one of the
most compelling motivations behind this is to <I>separate things that change
from things that stay the same</I>. Another way to put this is that once you
find some part of your program that&#8217;s likely to change for one reason or
another, you&#8217;ll want to keep those changes from propagating other changes
throughout your code. Not only does this make the code much cheaper to maintain,
but it also turns out that it is usually simpler to understand (which results in
lowered costs).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Often, the most difficult part of
developing an elegant and cheap-to-maintain design is in discovering what I call
&#8220;the
<A NAME="Index2904"></A><A NAME="Index2905"></A><A NAME="Index2906"></A>vector
of change.&#8221; (Here, &#8220;vector&#8221; refers to the maximum gradient and
not a collection class.) This means finding the most important thing that
changes in your system, or put another way, discovering where your greatest cost
is. Once you discover the vector of change, you have the focal point around
which to structure your design.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">So the goal of design patterns is
to isolate changes in your code. If you look at it this way, you&#8217;ve been
seeing some design patterns already in this book. For example,
<A NAME="Index2907"></A>inheritance can be thought of as a design pattern
(albeit one implemented by the compiler). It allows you to express differences
in behavior (that&#8217;s the thing that changes) in objects that all have the
same interface (that&#8217;s what stays the same).
<A NAME="Index2908"></A>Composition can also be considered a pattern, since it
allows you to change &#8211; dynamically or statically &#8211; the objects that
implement your class, and thus the way that class works.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">You&#8217;ve also already seen
another pattern that appears in <I>Design Patterns</I>: the
<A NAME="Index2909"></A><I>iterator</I> (Java 1.0<A NAME="Index2910"></A> and
1.1 capriciously calls it the <B>Enumeration</B>; Java
1.2<A NAME="Index2911"></A> collections use &#8220;iterator&#8221;<B>)</B>. This
hides the particular implementation of the collection as you&#8217;re stepping
through and selecting the elements one by one. The iterator allows you to write
generic code that performs an operation on all of the elements in a sequence
without regard to the way that sequence is built. Thus your generic code can be
used with any collection that can produce an
iterator.</FONT><A NAME="_Toc408018795"></A><BR></P></DIV>
<A NAME="Heading552"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">
The singleton</H3></FONT>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Possibly the simplest design
pattern is the <A NAME="Index2912"></A><I>singleton</I>, which is a way to
provide one and only one instance of an object. This is used in the Java
libraries, but here&#8217;s a more direct example:</FONT><BR></P></DIV>

<BLOCKQUOTE><FONT SIZE = "+1"><PRE><font color=#009900>//: SingletonPattern.java</font>
<font color=#009900>// The Singleton design pattern: you can</font>
<font color=#009900>// never instantiate more than one.</font>
<font color=#0000ff>package</font> c16;

<font color=#009900>// Since this isn't inherited from a Cloneable</font>
<font color=#009900>// base class and cloneability isn't added,</font>
<font color=#009900>// making it final prevents cloneability from</font>
<font color=#009900>// being added in any derived classes:</font>
<font color=#0000ff>final</font> <font color=#0000ff>class</font> Singleton {
  <font color=#0000ff>private</font> <font color=#0000ff>static</font> Singleton s = <font color=#0000ff>new</font> Singleton(47);
  <font color=#0000ff>private</font> <font color=#0000ff>int</font> i;
  <font color=#0000ff>private</font> Singleton(<font color=#0000ff>int</font> x) { i = x; }
  <font color=#0000ff>public</font> <font color=#0000ff>static</font> Singleton getHandle() { 
    <font color=#0000ff>return</font> s; 
  }
  <font color=#0000ff>public</font> <font color=#0000ff>int</font> getValue() { <font color=#0000ff>return</font> i; }
  <font color=#0000ff>public</font> <font color=#0000ff>void</font> setValue(<font color=#0000ff>int</font> x) { i = x; }
}

<font color=#0000ff>public</font> <font color=#0000ff>class</font> SingletonPattern {
  <font color=#0000ff>public</font> <font color=#0000ff>static</font> <font color=#0000ff>void</font> main(String[] args) {
    Singleton s = Singleton.getHandle();
    System.out.println(s.getValue());
    Singleton s2 = Singleton.getHandle();
    s2.setValue(9);
    System.out.println(s.getValue());
    <font color=#0000ff>try</font> {
      <font color=#009900>// Can't do this: compile-time error.</font>
      <font color=#009900>// Singleton s3 = (Singleton)s2.clone();</font>
    } <font color=#0000ff>catch</font>(Exception e) {}
  }
} <font color=#009900>///:~</font></PRE></FONT></BLOCKQUOTE>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">The key to creating a singleton is
to prevent the client programmer from having any way to create an object except
the ways you provide. You must make all
<A NAME="Index2913"></A><A NAME="Index2914"></A>constructors <B>private</B>, and
you must<B> </B>create at least one constructor to prevent the compiler from
<A NAME="Index2915"></A><A NAME="Index2916"></A>synthesizing a default
constructor for you (which it will create as
&#8220;friendly&#8221;).</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">At this point, you decide how
you&#8217;re going to create your object. Here, it&#8217;s created statically,
but you can also wait until the client programmer asks for one and create it on
demand. In any case, the object should be stored privately. You provide access
through public methods. Here, <B>getHandle(&#160;)</B> produces the handle to
the <B>Singleton</B> object. The rest of the interface (<B>getValue(&#160;)</B>
and <B>setValue(&#160;)</B>) is the regular class interface.</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Java also allows the creation of
objects through cloning. In this example, making the class <B>final</B> prevents
cloning. Since <B>Singleton</B> is inherited directly from <B>Object</B>, the
<B>clone(&#160;)</B> method remains <B>protected</B> so it cannot be used (doing
so produces a compile-time error). However, if you&#8217;re inheriting from a
class hierarchy that has already overridden <B>clone(&#160;)</B> as
<B>public</B> and implemented <B>Cloneable</B>, the way to prevent cloning is to
override <B>clone(&#160;)</B> and throw a <B>CloneNotSupportedException</B> as
described in Chapter 12. (You could also override <B>clone(&#160;)</B> and
simply return <B>this</B>, but that would be deceiving since the client
programmer would think they were cloning the object, but would instead still be
dealing with the original.)</FONT><BR></P></DIV>
<DIV ALIGN="LEFT"><P><FONT FACE="Georgia">Note that you aren&#8217;t
restricted to creating only one object. This is also a technique to create a
limited pool of objects. In that situation, however, you can be confronted with
the problem of sharing objects in the pool. If this is an issue, you can create
a solution involving a check-out and check-in of the shared
objects.</FONT><A NAME="_Toc408018796"></A><BR></P></DIV>
<A NAME="Heading553"></A><FONT FACE = "Verdana"><H3 ALIGN="LEFT">

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -