Anda di halaman 1dari 15

Design Pattern

Q1. What is a software design pattern?


A design pattern is a solution to a general software problem within a particular
context.
Context : A recurring set of situations where the pattern applies.
Problem : A system of forces (goals and constraints) that occur repeatedly in this
context.
Solution : A description of communicating objects and classes (collaboration) that
can be applied to resolve those forces. Design patterns capture solutions that have
evolved over time as developers strive for greater flexibility in their software. Whereas
class libraries are reusable source code and components are reusable pac!aged
objects patterns are generic reusable design descriptions that are customi"ed to solve
a specific problem. #he study of design patterns provides a common vocabulary for
communication and documentation and it provides a
framewor! for evolution and improvement of existing patterns.
$%. Why is the study of patterns important&
As initial software designs are implemented and deployed programmers often
discover improvements which ma!e the designs more adaptable to change. Design
patterns capture solutions that have evolved over time as developers strive for greater
flexibility in their software and they document the solutions in a way which
facilitates their reuse in other possibly unrelated systems. Design patterns allow us to
reuse the !nowledge of experienced software designers. 'oreover the study of design
patterns provides a common vocabulary for communication anddocumentation and it
provides a framewor! for evolution and improvement of existing patterns. As an
analogy consider that during a discussion among programmers the words (stac!) and
(tree) can be used freely without explanation. *oftware developers understand
fundamental data structures such as a (stac!) because these data structures are well
documented in textboo!s and are taught in computer science courses. #he study of
design patterns will have a similar (but more profound) effect by allowing designers
to say (composite pattern) or (observer pattern) in a particular design context
without having to describe all classes relationships and collaborations which ma!e
up the pattern. +atterns raise the level of abstraction when discussing and
documenting software designs.
$,. -ow do . document a design pattern&
A pattern description must address the following major points/
Pattern ame and Classification : A short meaningful name for the pattern
usually only one or two words. 0ames provide a vocabulary for patterns and they
have implied semantics 1 choose names carefully. 2ollowing the 3o2 boo! we can
also group patterns into higher level classifications such as creational structural
and behavioral patterns.
Problem : A general description of the problem context and the goals and
constraints that occur repeatedly in that context. A concrete motivational scenario
can be used to help describe the problem. #he problem description should provide
guidance to assist others in recogni"ing situations where the pattern can be applied.
Solution : #he classes and4or objects that participate in the design pattern their
structure (e.g. in terms of a 5'6 class diagram) their responsibilities and their
collaborations. #he solution provides an abstract description that can be applied in
many different situations. *ample 7ode in an object8oriented language can be used
to illustrate a concrete reali"ation of the pattern.
Conse!uences : A discussion of the results and tradeoffs of applying the pattern.
9ariations and language8dependent alternatives should also be addressed.
"nown #ses : :xamples of the pattern in real systems. 6oo! for applications of the
pattern in language libraries and framewor!s published system descriptions text
boo!s etc. 0ot every good solution represents a pattern. A general rule of thumb is
that a candidate pattern (also called a (proto8pattern)) should be discovered in a
minimum of three existing systems before it can rightfully be called a pattern.
#he following ;uote by <obert 'artin highlights the importance of providing pattern
descriptions/ (#he revolutionary concept of the 3o2 boo! is not the fact that there are
patterns= it is the way in which those patterns are documented. ... +rior to the 3o2
boo! the only good way to learn patterns was todiscover them in design
documentation or (more probably) code.)
$>. Where can . learn more about design patterns&
#he best place to start is the seminal wor! by :rich 3amma <ichard -elm <alph
?ohnson and ?ohn 9lissides (collectively !nown as the (3ang of 2our) or simply
(3o2)) entitled Design Patterns: Elements of Reusable Object-Oriented Software
(Addison8Wesley @AAB).
Warning: #his boo! is not light reading. 2rom the +reface/ (DonCt worry if you donCt
understand this boo! completely on the first reading. We didnCt understand it all on the
first writing.)
.t is however a boo! which wears well over time and it is definitely worth the effort
re;uired to wor! through it. Deyond the 3o2 boo! consider the list of references in
the Design +atterns section of this bibliography on object technology plus the
following web lin!s/
Design +atterns -ome +age
-uston Design +atterns
Drad AppletonCs *oftware +atterns 6in!s
7etus +atterns 6in!s
Q$. What is an example of a design pattern?
2ollowing the lead of the (3ang of 2our) (3o2) design pattern descriptions usually
contain multiple sections including
.ntent
'otivation
Applicability
*tructure
+articipants
7ollaborations
7onse;uences
.mplementation
*ample 7ode
Enown 5ses
<elated +atterns
A complete discussion of even a small pattern is beyond the scope of a simple 2A$
entry but it is possible to get the idea by examining an abbreviated discussion of one
of the simplest and most easily understood patterns. 7onsider the *ingleton pattern
whose intent reads as follows/
%ntent: :nsure that a class has one instance and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach
for solving it in a general way 1 some solutions are better than others. #he solution
offered by the 3o2 would loo! something li!e the following when coded in ?ava.
public class *ingleton
F
private static *ingleton instance G null=
public static *ingleton get.nstance()
F
if (instance GG null)
instance G new *ingleton()=
return instance=
H
protected *ingleton() F ... H
44 possibly another constructor form
public void some'ethod() F ... H
44... other methods
H
#he programmer would access the single instance of this class by writing something
similar
to
*ingleton.get.nstance().some'ethod()
or similar to
*ingleton s G *ingleton.get.nstance()=
s.method@()=
...
s.method%()=
...
2or a more complete discussion of the *ingleton pattern see the chapter (*ingleton)
in the boo! Design Patterns: Elements of Reusable Object-Oriented Software by the
(3ang of 2our) (Addison8Wesley @AAB) or the chapter (*ingleton) in the boo!
Patterns in Java, Volume by 'ar! 3rand (?ohn Wiley I *ons @AAJ). 2or
information about variations on the *ingleton +attern see the chapter entitled (#o Eill
a *ingleton) in the boo! Pattern !atc"ing: Design Patterns #$$lied by ?ohn
9lissides or the article %&m$lementing t"e Singleton Pattern in Java' by <od
Waldhoff.
Q&. Calendar is an abstract class. 'he get%nstance() method
tries to instantiate *regorianCalendar() i.e.+ parent instantiating a deri,ed class.
'his loo-s on.//? 0x: Calendar a1Calendar.get%nstance()2 Can somebod3
explain wh3 is it so?
#he 7alender class is an abstact class true howeverthe point you missed is that the
get.nstance() returns the K 7alendar using the default time"one and locale. K in your
case the 3regorian7alender a class that .* a 7alender (a *u"u!i .* a car a L>L .* a
plane..the standard MM terminology. *o what you get is a class that does some
speciali"ed wor! based on the default locale. Mther methods
public static synchroni"ed 7alendar get.nstance(#imeNone "one6ocale a6ocale)
public static synchroni"ed 7alendar get.nstance(#imeNone "one)
return 7alenders for specific time"ones and locales. #he closest parallel is possibly
the 2actory 'ethod design pattern.
$L. What major patterns do the ?ava A+.s utili"e&
Design patterns are used and supported extensively throughout the ?ava A+.s. -ere
are some examples/
#he 'odel89iew87ontroller design pattern is used extensively throughout the *wing
A+..
#he get.nstance() method in java.util.7alendar is an example of a simple form of
the 2actory 'ethod design pattern.
#he classes java.lang.*ystem and java.s;l.Driver'anager are examples of the
*ingleton pattern although they are not implemented using the approach
recommended in the 3o2 boo! but with static methods.
#he +rototype pattern is supported in ?ava through the clone() method defined in
class Mbject and the use of java.lang.7loneable interface to grant permission for
cloning.
#he ?ava *wing classes support the 7ommand pattern by providing an Action
interface and an AbstractAction class.
#he ?ava @.@ event model is based on the observer pattern. .n addition the
interface java.util.Mbservable and the class java.util.Mbserver provide support for
this pattern.
#he Adapter pattern is used extensively by the adapter classes in java.awt.event.
#he +roxy pattern is used extensively in the implementation of ?avaCs <emote
'ethod .nvocation (<'.) and .nterface Definition 6anguage (.D6) features.
#he structure of 7omponent and 7ontainer classes in java.awt provide a good
example of the 7omposite pattern.
#he Dridge pattern can be found in the separation of the components in java.awt
(e.g. Dutton and 6ist) and their counterparts in java.awt.peer.
$J. -ow can . ma!e sure at most one instance of my class is ever created&
#his is an instance where the *ingleton design pattern would be used. Oou need to
ma!e the constructor private (so nobody can create an instance) and provide a static
method to get the sole instance where the first time the instance is retrieved it is
created/
public class 'ine F
private static 'ine singleton=
private 'ine() F
H
public static synchroni"ed 'ine get.nstance() F
if (singleton GG null) F
singleton G new 'ine()=
H
return singleton=
H
44 other stuff...
H
Q4. When would % use the delegation pattern instead of inheritence to extend a
class5s beha,ior?
Doth delegation and inheritance are important concepts in object8oriented software
design but not everyone would label them as patterns. .n particular the seminal boo!
ondesign patterns by the (3ang of 2our) contains a discussion of inheritance and
delegation but the authors do not treat these topics as specific patterns. .t is
reasonable to thin! of them as design concepts which are more general than
specificdesign patterns.
.nheritance is a relationship between two classes where one class called a subclass in
this context inherits the attributes and operations of another class called its
superclass. .nheritance can be a powerful design4reuse techni;ue especially when it is
used in the context of the 6is!ov *ubstitution +rinciple. (#he article by <obert 'artin
at http/44www.objectmentor.com4publications4lsp.pdf provides an excellent
explanation of the ideas behind Darbara 6is!ovPs original paper on using inheritance
correctly.)
#he primary advantages of inheritance are
@. it is directly supported by object8oriented languages and
%. it provides the context for polymorphism in strongly8typed object8oriented
languages such as 7QQ and ?ava. Dut since the inheritance relationship is defined at
compile8time a class canPt change its superclass dynamically during program
execution. 'oreover modifications to a superclass automatically propagate to the
subclass providing a two8edged sword for software maintenance and reuse. .n
summary inheritance creates a strong static coupling between a superclass and its
subclasses.
Delegation can be viewed as a relationship between objects where one object
forwards
certain method calls to another object called its delegate. Delegation can also a
powerful
design4reuse techni;ue. #he primary advantage of delegation is run8time flexibility 1
the
delegate can easily be changed at run8time. Dut unli!e inheritance delegation is not
directly
supported by most popular object8oriented languages and it doesnPt facilitate
dynamic
polymorphism.
As a simple example consider the relationship between a <ectangle class and a
Window
class. With inheritance a Window class would inherit its rectangular properties from
class
<ectangle. With delegation a Window object would maintain a reference or pointer to
a
<ectangle object and calls to rectangle8li!e methods of the Window object would be
delegated to corresponding methods of the <ectangle object.
0ow letPs consider a slightly more complex example. *uppose employees can
classified
based on how they are paid= e.g. hourly or salaried. 5sing inheritance we might
design
three classes/ an :mployee class which encapsulates the functionality common to all
employees and two subclasses -ourly:mployee and *alaried:mployee which
encapsulates
pay8specific details. While this design might be suitable for some applications we
would
encounter problems in a scenario where a person changes say from hourly to salaried.
#he
class of an object and the inheritance relationship are both static and objects canPt
change
their class easily (but see the *tate pattern for tips on how to fa!e it).
A more flexible design would involve delegation 1 an :mployee object could delegate
payrelated
method calls to an object whose responsibilities focused solely on how the employee
is paid. .n fact we might still use inheritance here in a slightly different manner by
creating
an abstract class (or interface) called +ay7lassification with two subclasses
-ourly+ay7lassification and *alaried+ay7lassification which implement
classification8specific
computations. 5sing delegation as shown it would be much easier to change the pay
classification of an existing :mployee object.
#his second example illustrates an important point/ .n implementing delegation we
often
want the capability to replace the delegate with another object possibly of a different
class.
#herefore delegation will often use inheritance and polymorphism with classes of
potential
delegates being subclasses of an abstract class which encapsulates general delegate
responsibilities.
Mne final point. *ometimes the choice between delegation and inheritance is driven
by
external factors such as programming language support for multiple inheritance or
design
constraints re;uiring polymorphism. 7onsider threads in ?ava. Oou can associate a
class
with a thread in one of two ways/ either by extending (inheriting) directly from class
#hread or by implementing the <unnable interface and then delegating to a #hread
object.
Mften the approach ta!en is based on the restriction in ?ava that a class can only
extend
one class (i.e. ?ava does not support multiple inheritance). .f the class you want to
associate with a thread already extends some other class in the design then you would
have to use delegation= otherwise extending class #hread would usually be the
simpler
approach.
Q16. Which patterns were used b3 Sun in designing the 0nterprise 7a,a8eans
model?
'any design patterns were used in :?D and some of them are clearly identifiable by
their naming convention. -ere are several/
@. 9actor3 :ethod: Define a interface for creating classes let a subclass (or a helper
class) decide which class to instantiate.#his is used in :?D creation model. :?D-ome
defines an interface for creating the :?DMbject implementations. #hey are actually
created by a generated container class. *ee .nitial7ontext2actory interface that returns
an .nitial7ontext based on a properties hashtable.
%. Singleton: :nsure a class has only one instance and provide a global point of
access to it. #here are many such classes.
Mne example is javax.naming.0aming'anager
,. ;bstract 9actor3: +rovide an interface for creating families of relegated or
dependent objects without specifying their concrete classes.
We have interfaces called .nitial7ontext .nitial7ontext2actory. .nitial7ontext2actory
has methods to get .nitial7ontext.
>. 8uilder: *eparate the construction of a complex factory from its representation so
that the same construction process can create different representations.
.nitial7ontext2actoryDuilder can create a .nitial7ontext2actory.
B. ;dapter: 7onvert the interface of a class into another interface clients expect.
.n the :?D implementation model we implement an :?D in a class that extends
*essionDean or a :ntityDean. We donCt directly implement the :?DMbject4home
interfaces. :?D container generates a class that adapts the :?DMbject interface by
forwarding the calls to the enterprise bean class and provides declarative
transaction persistence support.
R. Prox3: +rovide a surrogate for other object to control access to it.
We have remote <'.87M<DA proxies for the :?DCs.
L. :emento: Without violating encapsulation capture and externali"e an objectCs
internal state so that the object can be restored to this state later.
7ertainly this pattern is used in activating4passivating the enterprise beans by the
container4server.
Q11. What is an anal3sis pattern?
An analysis pattern is a software pattern not related to a language or implementation
problem but to a business domain such as accounting or health care. 2or example in
health care the patient visit activity would be subject to a number of patterns.
#here is a good overview from an MM+*6A CAR presentation at
http/44www.jeffsutherland.org4oopslaAR4fowler.html
; good text would be: 'artin 2owlerCs 'artin #nal(sis Patterns : Reusable Object
)odels
.*D0/ S%S@JAB>%S published by Addison8Wesley. .n summary analysis patterns are
useful for discovering and capturing business processes.
Q1<. What are the differences between anal3sis patterns and design patterns?
Analysis pattern are for domain architecture and design pattern are for
implementation mechanism for some aspect of the domain architecture. .n brief
analysis pattern are more high level and more (end8user) functional oriented.
Q1=. >ow does ?0xtreme Programming? (@P) fit with patterns?
:xtreme +rogramming has a large emphasis on the concept of refactoring/ Writing
codeonce and only once. +atterns particularly the structural patterns mentioned by the
3ang of 2our can give good pointers about how to acheive that goal.
(T+ states when and where factoring should happen patterns can show you how.)
Q1A. What is the disad,antage of using the Singleton pattern? %t is enticing to
use this pattern for all the classes as it ma-es it eas3 to get the reference of the
singleton obBect.
#he intent of the *ingleton pattern is to ensure a class has only one instance and to
provide a global point of access to it. #rue the second part about providing a global
point of access is enticing but the primary disadvantage of using the*ingleton pattern
for all classes is related to the first part of the intent= i.e. that it allows only one
instance of the class. 2or most classes in an application you will need to create
multiple instances. What purpose would a 7ustomer class serve if you could
createonly one 7ustomer object&
Q1$. >ow do 3ou write a 'hread.Safe Singleton?
. have written plenty of non8thread8safe *ingletons but it wasnCt until recently when .
trac!ed it down that . reali"ed that thread8safety could be a big problem.
#he problem is that in the typical *ingleton implementation (at least the ones .Cve
seen) there is the ability to create multiple versions of the single instance.... !now
KDut -ow&K. Well in the get.nstance() call the instance is chec!ed for null and then
immediately constructed if it is null and then the instance is returned.
#he problem is that the thread (#a) ma!ing the call could swap8out immediately after
chec!ing for a null. A subse;uent thread (#b) could then ma!e a call to get the
instance and construct an instance of the*ingleton. When the original thread (#a) is
then swapped bac! in it would construct and return a completely separate object.
DAD E.##OU
#he following code snippet shows an example of a thread8safe *ingleton.
pac!age com.jg!.patterns.singleton=
public class ?3E*ingleton F
4V -ere is the instance of the *ingleton V4
private static ?3E*ingleton instanceW=
4V 0eed the following object to synchroni"e V4
4V a bloc! V4
private static Mbject syncMbjectW=
4V +revent direct access to the constructor
private ?3E*ingleton() F
super()=
H
public static ?3E*ingleton get.nstance() F
4V in a non8thread8safe version of a *ingleton V4
4V the following line could be executed and the V4
4V thread could be immediately swapped out V4
if (instanceW GG null) F
synchroni"ed(syncMbjectW) F
if (instanceW GG null) F
instanceW G new ?3E*ingleton()=
H
H
H
return instanceW=
H
H
*O+E: +"e ,nd c"ec- for if .instance/ 00 null1 is needed to avoid ma-ing anot"er
unnecessar(
construct2
Q1&. What is the Ceactor pattern?
#he new boo! K+attern8oriented *oftware Architecture 9olume %K .*D0 S>L@RSRAB%
has a chapter on the <eactor pattern. .t falls under the general category of K:vent
-andling +atternsK. #o ;uote the leading bit of the chapter K#he <eactor architectural
pattern allows event8driven applications to demultiplex and
dispatch service re;uests that are delivered to an application from one or more clientsK
.t is used in a synchronous manner so that if the callbac! you delegate the event to
ta!es a while to complete you will run into problems with scalability.
$@L. What are +rocess +atterns&
Dasically process patterns define a collection of best practices techni;ues methods
for developing object8oriented software. A good reference site is by *cott Ambler. -e
also has two boo!s on the topic plus a white paper on the subject you can download.
http/44www.ambysoft.com4process+atterns+age.html.
Q1D. >ow and where did the concept of design patterns get started?
Wor! on patterns has been influenced by the wor!s of 7hristopher Alexander who
published on topics related to urban planning and building architecture in the late
@ALSs. #he history of patterns for software design began in the late @AJSs and reached
an important milestone with the publishing of the first boo! fully dedicated to this
subject by the K3ang of 2ourK :rich 3amma <ichard -elm <alph ?ohnson and ?ohn
9lissidesDesign +atterns 1 :lements of <eusable Mbject8Mriented *oftware). .n
conjunction the emergence of object8oriented software development fostered the
wor! on other topics related todesign patterns such as application framewor!s
analysis patterns language idioms and so on.
Q14. Where can % find good examples of the Protot3pe pattern?
#he prototype pattern is actually ;uite simple to implement in ?ava. <ecall that the
idea of prototype is that you are passed an object and use that object as a template to
create a new object. Decause you might not !now the implementation details of
the object you cannot create a new instance of the object and copy all of its data.
(*ome of the data may not be accessible via methods). *o you as! the object itself to
give you a copy of itself. ?ava provides a simple interface named 7loneable that
provides an implementation of the +rototype pattern. .f you have an object that is
7loneable you can call its clone() method to create a new instance of the object with
the same values. #he tric! here is that you must override the clone() method to
increase its visibility and just call super.clone(). #his is because the implementation
of clone() defined in java.lang.object is protected.
2or example/
public class 7opy'e implements 7loneable F
public Mbject clone() F
return super.clone()=
H
H
0ote that 7loneable is an empty interfaceU .t merely acts as a tag to state that you
really want instance of the class to be cloned. .f you donCt implement 7loneable the
super.clone() implementation will throw a 7lone0ot*upported:xception.
#he Mbject implementation of clone() performs a s"allow co$( of the object in
;uestion. #hat is it copies the values of the fields in the object but not any actual
objects that may be pointed to. .n other words the new object will point to the same
objects the old object pointed to.
As an example of using the cloning/
7opy'e thing G new 7opyme()=
7opy'e another#hing G (7opyme)thing.clone()=
#his example is pretty trivial but the real power comes when you donCt !now what
youCre actually cloning.
2or example suppose you define an interface that represents a customer/
public interface 7ustomer extends 7loneable F
public Mbject clone()= 44 re;uire ma!ing it publicU
public *tring get0ame()=
public void set0ame(*tring name)=
...
H
Oou might have several different implementations of this interface possibly storing
data in a file database or using :?D :ntity beans. .f a shallow copy of the data is
sufficient to represent a copy of the object ?avaCs clone() method wor!s great.
Oou might have a method that needs to ma!e a copy of the data to store it in a
-ashtable for example/
public void store7ustomer(7ustomer customer) F
7ustomer copy G (7ustomer)customer.clone()=
data*tore.put(copy)=
H
0ote that this method !nows not"ing about what type of customer weCre getting. #his
pattern will wor! for an( actual type of 7ustomer no matter how the data is stored.
2or example/
2ileDased7ustomer c@ G new 2ileDased7ustomer(...)=
<DD'*Dased7ustomer c% G new <DD'*Dased7ustomer(...)=
:?DDased7ustomer c, G new :?DDased7ustomer(...)=
manager.store7ustomer(c@)=
manager.store7ustomer(c%)=
manager.store7ustomer(c,)=
Q<6. What are ;nti.Patterns?
#here isnCt really a Kclean8cutK definition out there just yet unli!e Design +atterns.
Dasically as Design +atterns (and more particularly +rocess +atterns) try to codify a
standard vocabulary for wor!ing solutions to problems that reappear fre;uently Anti8
+atterns represent an effort to define and classify reoccuring non8solutions i.e. things
that lots of projects do that fail to yield a solution or actually prevent a project from
wor!ing or being finished. #he most basic example . can thin! of is K#he -ammerK
inspired by the old addage K.f your only tool is a hammer everything loo!s li!e a
nailK (or the variation K.f your only tool is a hammer everything loo!s li!e your left
thumb.K -ammer describes a regular reoccuring problem in inexperienced engineers
(particularly those whoCve only used one language for the bul! of their carreer so far)
that of trying to force8feed all problems into
the solutions they already !now.
http/44www.antipatterns.com4 has more information.
Q<1. What patterns are particularl3 useful in building networ-ed applications?
. suggest starting with +attern8Mriented *oftware Architecture/ +atterns for
7oncurrent and 0etwor!ed Mbjects (+M*A%). +M*A% specifically brings together @L
interrelated patterns addressing Service #ccess and 3onfiguration, Event !andling,
S(nc"roni4ation, and 3oncurrenc(. #he patterns and many of the examples in +M*A%
come primarily from the design and implementation of the A7: framewor!.
Q<<. ;re there an3 good 7a,a.specific patterns boo-s a,ailable?
#he ?ava8specific patterns boo!s are/
?ava Design +atterns/ A #utorial
+atterns in ?ava 9olume @
+atterns in ?ava 9olume %
7oncurrent +rogramming in ?ava *econd :dition/ Design +rinciples and +atterns
*an2rancisco Design +atterns
As far as the good part of the ;uestion.... Doug 6eaCs 3oncurrent Programming boo!
is
probably the best of the bunch. -owever its patterns are specific to concurrent
programming. 'any people donCt li!e the ;uality of 'ar! 3randCs two Patterns in
Java
boo!s. X#hey are rated , and % stars at Ama"on respectivelyY. #he first printing of the
7ooper tutorial boo! was riddled with errors. .f you get that be sure to get at least the
second printing. X6oo! on last line of page before #M7.Y #he *an2rancisco boo! is
definitely good but .Cm not sure how good if you arenCt using *2.
Q<=. What are Collaboration Patterns?
7ollaboration +atterns are repeatable techni;ues used by teams of people to help them
wor! together (collaborate). :llen 3ottesdiener of :D3 7onsulting has created these
patterns in order to help facilitate good teamwor!. #hese patterns really have nothing
to do with object8oriented development or ?ava besides the fact that they can help
with re;uirements gathering or 7<7 design sessions. .n a nutshell 7ollaboration
+atterns are techni;ues to help ma!e meetings useful.
Q<A. %s it correct from a design point of ,iew to ma-e an obBect both an /bser,er
and /bser,able at the same time?
Oes and this can be the preferred pattern in some cases.
2or example suppose you were writing a supply chain management system for a
retail chain. :ach store object in your system generates item8sold events= when the
chain generates enough of these for a particular product a buyer object generates a
purchase order for more of the product. -owever the buyer object has no particular
interest in individual item sold events. .nstead the buyer (Mbserver) registers to
receive out8of8stoc! events from the warehouse (Mbservable)= the warehouse as
Mbserver registers with the individual stores (Mbservables) to receive item8sold
events. #hus the warehouse is both Mbserver and Mbservable. (+lease note that this is
a synthetic example and probably not the way to organi"e a supply chain.)
Another reason to use one or more central Mbserver8Mbservable object in between
ultimate Mbservers and Mbservables is to fully decouple the two. .n some cases
Mbserver and Mbservable may exist on different machines and may rely on the
central Mbserver8 Mbservable to hide this complication. A good source for more
details is the +ublisher8*ubscriber section of Duschmann et al.
Pattern-Oriented Software #rc"itecture: # S(stem of Patterns2
Q<$. >ow can % maintain a single instance of an obBect in an applet?
.n start() instead of always creating a new object return the existing one if it exists or
create a new one if it doesnCt.
Q<&. What is the best wa3 to generate a uni,ersall3 uni!ueobBect %D? Do % need
to use an external resource li-e a file
or database+ or can % do it all in memor3?
. need to generate uni;ue idCs that will be used for node C.DC attribute values within
T'6 documents. #his id must be uni;ue system8wide. #he generator must be
available to a number of servlets that add various node structures to my T'6 docs as
a service. What is the best way to tac!le this& #he CpossibleC ways . can see/
Eeep the maximum .D value in a flat8file where the service would read it upon
startup and increment it. 5pon shutdown or failure it would write the latest max id to
the file.
7alculate the max id by searching the T'6 itself. #his will be tougher since T'6
re;uires an alpha8numeric value (not strictly numeric).
5se a database ('y*$6) with a two8field table where one field is the incremental
counter.
. just have this feeling that none of the above are the most efficient ways of doing this.
<egards 8AndyY #here is an additional way to do that that doesnCt rely on an external
file (or database) li!e the one you have presentred. .f has been presented in the
:?DDesign +atterns boo! written by 2loyd 'arinescu and available in a pdf format
for free from the given lin!. #he suggested solution is based on the 55.D for :?D
pattern that comes out from this ;uestion/
!ow can universall( uni5ue $rimar( -e(s can be generated in menor( wit"out
re5uiring a
database or a singleton6
Without enetring in the specifics (you can fully chec! out the pattern by reading the
appropriate chapter) the solution is to generate a ,% digit !ey encoded in
hexadecimal composed as follows/
@. 5ni;ue down to the millisecond. Digits @8J are are the hex encoded lower ,% bits of
the *ystem.current#ime'illis() call.
%. 5ni;ue across a cluster. Digits A8@R are the encoded representation of the ,% bit
integer of the underlying .+ address.
,. 5ni;ue down to the object in a ?9'. Digits @L8%> are the hex representation of the
call to *ystem.identity-ash7ode() which is guaranteed to return distinct integers for
distinct objects within a ?9'.
>. 5ni;ue within an object within a millisecond. 2inally digits %B8,% represent a
random ,% bit integer generated on every method call using the cryptographically
strong java.security.*ecure<andom class.
Q<E. %s there some -ind of Design pattern which would ma-e it possible to use
the Same code base in 078 and non
078 context?
A good suggestion would be using Delegation
class +ieceMf7ode F
public Mbject my'ethod() FH
H
class :?D.mpl ... F
+ieceMf7ode poc G new +ieceMf7ode()=
public Mbject my'ethod() F
return poc.my'ethod()=
H
H
#his should not be a violation of :?D specs since :?Ds can use simple java classes
for their use. #hin! about De$endant Objects and so on.

Q<D. What is session facade?
Session facade is one design pattern that is often used while developing enterprise
applications. .t is implemented as a higher level component (i.e./ *ession :?D) and it
contains all the iteractions between low level components (i.e./ :ntity :?D). .t then
provides a single interface for the functionality of an application or part of it and it
decouples lower level components simplifying the design. #hin! of a ban! situation
where you have someone that would li!e to transfer money from one account to
another. .n this type of scenario the client has to chec! that the user is authori"ed get
the status of the two accounts chec! that there are enough money on the first one and
then call the transfer. #he entire transfer has to be done in a single transaction
otherwise is something goes south the situation has to be restored. As you can see
multiple server8side objects need to be accessed and possibly modified. 'ultiple fine8
grained invocations of :ntity (or even *ession) Deans add the overhead of networ!
calls even multiple transaction. .n other words the ris! is to have a solution that has a
high networ! overhead high coupling poor reusability and maintainability. #he best
solution is then to wrap all the calls inside a *ession Dean so the clients will have a
single point to access (that is the session bean) that will ta!e care of handling all the
rest. Mbviously you need to be very careful when writing *ession 2acades to avoid
the abusing of it (often called K3od8DeanK).2or a detailed description of this pattern
chec! this page/ 7ore ?%:: +atterns 1 *ession 2acade or get 2loyd 'arinescuCs :?D
Design +atterns in +D2 format.
Q<4. >ow is 7D/ different from F/ ?
?DM is a persistence technology that competes against entity beans in enterprise
application development. .t allows you to create +M?Ms (plain old java objects) and
persist them to the database 8 letting ?DM ta!e care of the storage. 9alue objects on
the other hand represent an abstract design pattern used in conjuction with entity
beans jdbc and possibly even ?DM to overcome commonly found isolation and
transactional problems in enterprise apps. 9alue objects alone do not allow you to
persist objects 8 they are simple data holders used to transfer data from the database to
the client and bac! to the database. *ide note/ . !now that many boo!s out there still
refer to these data holders as value objects but the correct term is D+O: data transfer
objects. 9alue objects refer to objects that hold a value. A good example of this
java.lang..nteger object which holds an int.
Q=6. >ow can % implement the :FC design pattern using 7SP?
#he '97 ('odel 9iew 7ontroller) design pattern is a pattern4architecture that can be used by
35.Cs. .t seperates the applicationCs data user interface and control logic into three separate
entities. #his ensures the system will be more maintainable in the future as changes to one
component will not have an affect on the others.#he '97 pattern also conforms with the ?*+
'odel % architecture.#he '97 pattern can be easily implemented in web applications using
?*#6 core ?*+*ervlets and ?avaDeans. ?*#6 ma!es it easy for -#'6 designers to use
dynamic data in their pages without having to learn in depth java. #he tags are in a
recogni"able -#'6 li!e format meaning a smaller learning curve than ta!ing on the ?*+
specification after ta!ing on the ?ava specification. ?*#6 also ma!es it easy for web
developers who are developing all aspects of the application in helping you !eep the content
separate from the display by !eeping your ?*+ clean from any ?ava code.

Anda mungkin juga menyukai