330 likes | 567 Views
Design Patterns. Section 7.1 (JIA’s) Section 7.2.1 (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section 10.4.1 (JIA’s). Design Patterns. Pattern is a term used to describe architectural designs Recurring Problems in architectural designs (Christopher Alexander, 1977)
E N D
Design Patterns Section 7.1 (JIA’s) Section 7.2.1 (till page 259) (JIA’s) Section 7.2.2(JIA’s) Section 10.4.1 (JIA’s)
Design Patterns • Patternis a term used to describe architectural designs • Recurring Problems in architectural designs (Christopher Alexander, 1977) • describe solutions for those problems • A pattern is a generic or reusable solution to a recurring problem • Can that be applied to software?
Design Patterns • Similarities between software and architecture • Both are based on creative processes • Design must satisfy customer’s needs • Design my be feasible to engineer • Designers must balance many competing constraints and requirements • As a result, software design patterns are descriptions (templates) of solutions to recurring problems in software design • Not a finished design!
Design Patterns • Why use design patterns? • Why reinvent the wheel? Use (reuse) common solutions for common problems • Boost confidence in software systems --use established design patterns that have been proveneffective • Provide a common vocabulary for software designers to communicate about software design • Work started by Gamma et al. • Design Patterns [Gamma et al., 1995]
Design Patterns • 23 general-purpose design patterns [Gamma et al.] • Creational patterns • Deal with the process of object creation • E.g. Singleton --- One instance of class can exist • Structural patterns • Deal with the static composition and structure of classes and objects • E.g. Adapter --- Convert an interface of a class to a different one expected by other classes • Behavioral patterns • Deal with dynamic interaction among classes and objects • E.g. Template --- Separate variant and invariant behaviors among related classes
Design Patterns • Pattern name (Also known as) • Problem addressed • Detailed description • When to apply (list of preconditions) • The Solution • Class diagram that depicts the participants of the pattern and the relationships among them • A list of classes participating in the pattern • Does not describe a concrete solution, is a template instead • Describe results and tradeoffs
Singleton Design Pattern • Pattern name: Singleton • Category: Creational design pattern • Intent: Ensure that a class has only one instance and provides a global point of access to it • Also known as: N/A • Applicability: Use the Singleton pattern when there must be exactly one instance of a class and it must be accessible to clients from a well-known access point • a GUI application must have a single mouse • an active modem needs one and only one telephone line • an operating system can only have one window manager • or, a PC is connected to a single keyboard • Such objects are accessed by disparate objects throughout a software system, and therefore require a global point of access • Structure: NEXT SLIDE • Participants: Itself
Singleton • Declares the unique instance of the class as a static variable • Defines a static method getInstance() for clients to access the unique instance --- global access point • Code • public class Singleton { private static Singleton theOnlyOne = null;//usually has other instance variables as well private Singleton() { } public static Singleton getInstance() { // global access point if(theOnlyOne == null) { theOnlyOne = new Singleton(); } return theOnlyOne; }}
Singleton • public class SingletonInstantiator { • public SingletonInstantiator() { • Singleton instance = Singleton.getInstance(); • Singleton anotherInstance =new Singleton(); !!! } • } • Test if working properly?
Example Singleton public class SingleRandom { private Random gen; private static SingleRandom theOnlyOne = new SingleRandom(); private SingleRandom() {gen = new Random(); } public void setSeed(int seed) { gen.setSeed(seed); } public int nextInt() { return gen.nextInt(); } public static SingleRandom getInstance() { return theOnlyOne; }
Template Design Pattern • One of the most widely used design patterns • Useful for separating the variant and the invariant object behavior • Invariant means common to all subclasses • The invariant behavior is placed in the abstract class (template) • Concrete methods common to all subclasses • Abstract class contains abstract methods for the variant behavior • Any subclasses that inherit it can override the abstract methods and implement the specifics needed in that context • In the body of TemplateMethod() --- invariant --- there are calls to operation1() and operation2() … • operation1() and operation2() are abstract • defined by the subclasses which override them
Template Design Pattern • Why abstract classes for templates? • Contain behavior that is common to all its subclasses encapsulated in non-abstract methods • Might even be defined as final • The abstract methods in such a class require that context-specific behavior be implemented for each concrete subclass • Called Hook methods
Template Design Pattern • A program that sorts data using different sorting algorithms: • The AbstractClasswould have a method called Sort() • -- the invariant behavior • Sort uses the abstract methods in the class, which are specified by any class that inherits from it • The hook methods in this case might be • compare() (compares two objects and returns the one that is "higher") • sortPass() (performs one iteration of a particular sorting algorithm) • The usual control structure of object calls and relations is reversed! • It is the parent class that calls the method in the subclass
Template Design Pattern • Pattern Name: Template Method • Category: Behavioral design pattern • Intent:To define the skeleton of an algorithm deferring some steps to subclasses, thus allowing the subclasses to redefine certain steps of the algorithm • This way, subclasses can override parts of the algorithm without changing its overall structure • Applicability: The Template Method Pattern should be used • to implement the invariant parts of an algorithm once and leave it to the subclasses to implement variant behavior • localize the common behavior among subclasses to avoid code duplication
# #
Template Design Pattern • Participants: • Generic (or Abstract) Class • Defines theabstract hook methods (variant behavior) that concrete classes override to implement the steps of an algorithm • Implementsa template method (invariant behavior) that defines the skeleton of an algorithm called by the hook methods • Concrete Class • Implements the hook methodsto carry-out subclass-specific steps of the algorithm defined in the template method • Example 7.3 page 267 • www.users.csbsju.edu/~jschnepf/CS230/Code/Plotter/index.html
Adapter Design Pattern • Pattern Name: Adapter • Category: Structural design pattern • Intent: To convert the contract of a class into another contract that new clients expect • The Adapter pattern is used so that two incompatible interfaces can work together • The join between them is called an Adapter • We convert interface of one class into interface expected by the client • A.K.A: Wrapper • Applicability: when we need to use an existing class with a “different” interface than provided
Structure of Object Adapter Pattern • Object adapters use delegation to adapt one interface to another • The adapter implements the target interface that the client expects to see, while it holds an instance of the adaptee • Can extend adaptee instead (limited to a single adaptee) • Object (composition) vs. Class (inheritance) Adapter • When the client calls the request() method on its target object (the adapter), the request is translated into the corresponding specific request on the adaptee • Adapters enable the client and the adaptee to be completely decoupled from each other • Only the adapter knows about both of them
Structure of Class Adapter Pattern << >> Adaptee
Adapter Design Pattern • Participants • Client • Requires objects conforming toATarget • ATargetinterface • Defines the interface expected by the Client • Adaptee class • Defines the “undesired” interface of an existing class • Adapter • Adapts the interface of Adaptee toATarget via delegation (composition) or inhertince
CLIENT application would like to use a stack interface on DList (i.e. adapt ADAPTEE to TARGET) ADAPTEE /* DoubleLinkedList */ class DList { public void insert (int pos, Object o) { ... } public void remove (int pos, Object o) { ... } public void insertHead (Object o) { ... } public void insertTail (Object o) { ... } public Object removeHead () { ... } public Object removeTail () { ... } public Object getHead () { ... } public Object getTail () { ... } } TARGET interface Stack { void push (Object); Object pop (); Object peek(); } Example Object Adapter
ADAPTER /* Adapt DList class to Stack interface */ class DListStack implements Stack { private DList _dlist; public DListStack() {_dlist = new DList(); } publicvoid push (Object o) { _dlist.insertHead (o); } public Object pop () {return _dlist.removeHead ();} public Object peek() {return _dlist.getHead ();} } Example Object Adapter
/* Adapt DList class to Stack interface */ ADAPTER class DListImpStack extends DList implements Stack { publicvoid push (Object o) {insertHead (o); } public Object pop () {return removeHead (); } public Object peek() {return getHead(); } } Example Class Adaptor
Example (Object Adapter) • Example page 514-530 • Table (Generic display table) • Client • Expects entries of type TableEntry • ListTableModel • TableEntry (row in a table) • Target • Student (Information on a Student) • Adaptee • Does not conform to TableEntry • StudentEntry2 • Adapter • Adapts Student to TableEntry
Example (Class Adapter) • Table (Generic display table) • Client • Expects entries of type TableEntry • TableEntry (row in a table) • Target • Student (Information on a Student) • Adaptee • Does not conform to TableEntry • StudentEntry • Adapter • Adapts Student to TableEntry