4050 Design Pattern

64 %
36 %
Information about 4050 Design Pattern

Published on September 12, 2007

Author: Octavio

Source: authorstream.com

List of Design Patterns:  List of Design Patterns Creational Patterns Abstract Factory Builder Factory Method Prototype Singleton Structural Patterns Adapter Bridge Composite (Sammy’s Slides) Decorator (Sammy’s Slides) Facade Flyweight Proxy Behavioral Patterns Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor FACTORY METHOD (Class Creational):  FACTORY METHOD (Class Creational) Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. FACTORY METHOD:  FACTORY METHOD Structure Product Creator ConcreteProduct FactoryMethod() AnOperation() ConcreteCreator FactoryMethod() FACTORY METHOD:  FACTORY METHOD Participants Product Defines the interface of objects the factory method creates ConcreteProduct Implements the product interface Creator Declares the abstract factory method ConcreteCreator Overrides factory method to return instance of ConcreteProduct Collaborations Creator relies on its subclasses to implement the factory method so that it returns an instance of the appropriate ConcreteProduct Factory Example:  Factory Example public abstract class Pizza { String name; public String getName() { return name;} } public class NYStylePizza extends Pizza { name = 'NY Style Pizza'; } public class ChicagoStylePizza extends Pizza { name = 'Chicago Style Pizza'; } public abstract class PizzaStore { abstract Pizza createPizza(); } public class NYPizzaStore extends PizzaStore { Pizza createPizza() {return new NYStylePizza();} } public class ChicagoPizzaStore extends PizzaStore { Pizza createPizza() {return new ChicagoStylePizza();} } SINGELTON (Object Creational):  SINGELTON (Object Creational) Intent: Ensure a class only has one instance, and provide a global point of access to it. Motivation: Sometimes we want just a single instance of a class to exist in the system For example, we want just one window manager. Or just one factory for a family of products. We need to have that one instance easily accessible And we want to ensure that additional instances of the class can not be created Applicability:  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. when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code. SINGLETON:  Singleton return uniquelnstance static Instance() SingletonOperation() GetSingletonData() Static uniquelnstance singletonData SINGLETON Consequences Benefits Controlled access to sole instance Permits a variable number of instances Structure Participants and Collaborations:  Participants and Collaborations Singleton: Defines an instance operation that lets clients access its unique interface Instance is a class operation (static in Java) May be responsible for creating its own unique instance Collaborations: Clients access a Singleton instance solely through Singleton’s Instance operation. Singleton Example:  Singleton Example public class Singleton { // declare the unique instance of the class private static Singleton uniqueInstance = null; // private constructor only accessed from this class private Singleton() { } // Returns a reference to the single instance. // Creates the instance if it does not yet exist. // (This is called lazy instantiation.) public static Singleton getInstance() { if (uniqueInstance ==null){ uniqueInstance = new Singleton(); } return uniqueInstance; } // other methods } Singleton Example:  Singleton Example Note that the singleton instance is only created when needed. This is called lazy instantiation. Thought experiment: What if two threads concurrently invoke the instance() method? Any problem? Yup! Two instances of the singleton class could be created! How could we prevent this? Several methods: Make the instance() synchronized. Synchronization is expensive, however, and is really only needed the first time the unique instance is created. Do an eager instantiation of the instance rather than a lazy instantiation. Singleton Example eager instantiation :  Singleton Example eager instantiation public class Singleton { // eager instantiation private static Singleton uniqueInstance = new Singleton(); // private constructor only accessed from this class private Singleton() { } // Returns a reference to the single instance. public static Singleton getInstance() { return uniqueInstance; } // other methods } Adapter Pattern(Structural Pattern):  Adapter Pattern (Structural Pattern) Intent Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. Also Known As Wrapper Motivation Sometimes a toolkit or class library can not be used because its interface is incompatible with the interface required by an application We can not change the library interface, since we may not have its source code Even if we did have the source code, we probably should not change the library for each domain-specific application Adapter Pattern:  Adapter Pattern Motivation Example: Adapter Example:  Adapter Example Structure A class adapter uses multiple inheritance to adapt one interface to another: Adapter Example:  Adapter Example Structure An object adapter relies on object composition: Adapter Pattern:  Adapter Pattern Applicability: Use the Adapter pattern when You want to use an existing class, and its interface does not match the one you need You want to create a reusable class that cooperates with unrelated classes with incompatible interfaces Implementation Issues How much adapting should be done? Simple interface conversion that just changes operation names and order of arguments Totally different set of operations Does the adapter provide two-way transparency? A two-way adapter supports both the Target and the Adaptee interface. It allows an adapted object (Adapter) to appear as an Adaptee object or a Target object Adapter Example:  Adapter Example The classic round pegs and square pegs! Here's the SquarePeg class: /** * The SquarePeg class. * This is the Target class. */ public class SquarePeg { public void insert(String str) { System.out.println('SquarePeg insert(): ' + str); } } And the RoundPeg class: /** * The RoundPeg class. * This is the Adaptee class. */ public class RoundPeg { public void insertIntoHole(String msg) { System.out.println('RoundPeg insertIntoHole(): ' + msg); } } Adapter Example:  Adapter Example If a client only understands the SquarePeg interface for inserting pegs using the insert() method, how can it insert round pegs? A peg adapter! Here is the PegAdapter class: /** * The PegAdapter class. * This is the Adapter class. * It adapts a RoundPeg to a SquarePeg. * Its interface is that of a SquarePeg. */ public class PegAdapter extends SquarePeg { private RoundPeg roundPeg; public PegAdapter(RoundPeg peg) {this.roundPeg = peg;} public void insert(String str) {roundPeg.insertIntoHole(str);} } Adapter Example:  Adapter Example Typical client program: // Test program for Pegs. public class TestPegs { public static void main(String args[]) { // Create some pegs. RoundPeg roundPeg = new RoundPeg(); SquarePeg squarePeg = new SquarePeg(); // Do an insert using the square peg. squarePeg.insert('Inserting square peg...'); // Now we'd like to do an insert using the round peg. // But this client only understands the insert() // method of pegs, not a insertIntoHole() method. // The solution: create an adapter that adapts // a square peg to a round peg! PegAdapter adapter = new PegAdapter(roundPeg); adapter.insert('Inserting round peg...'); } } Observer Pattern:  Observer Pattern A behavioral (object) pattern: Concerns objects and their behavior. Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Also Known As Dependents, Publish-Subscribe, Model-View Motivation The need to maintain consistency between related objects without making classes tightly coupled Observer Pattern:  Observer Pattern Motivation Observer Pattern:  Observer Pattern Applicability: Use the Observer pattern in any of the following situations: When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently. When a change to one object requires changing others When an object should be able to notify other objects without making assumptions about those objects Observer Pattern – Structure:  Observer Pattern – Structure Observer Pattern - Participants:  Observer Pattern - Participants Subject Has a list of observers; interfaces for attaching/detaching an observer Observer An updating interface for objects that gets notified of changes in a subject. ConcreteSubject The object being observed Stores state of interest to observers Sends notification when state changes. ConcreteObserver Implements updating interface. Observer Pattern - Collaborations:  Observer Pattern - Collaborations Observer Pattern - Consequences:  Observer Pattern - Consequences Benefits Minimal coupling between the Subject and the Observer Can reuse subjects without reusing their observers and vice versa Observers can be added without modifying the subject All subject knows is its list of observers Subject does not need to know the concrete class of an observer, just that each observer implements the update interface Subject and observer can belong to different abstraction layers Support for event broadcasting Subject sends notification to all subscribed observers Observers can be added/removed at any time Observer Pattern - Consequences:  Observer Pattern - Consequences Liabilities Possible cascading of notifications Observers are not necessarily aware of each other and must be careful about triggering updates Simple update interface requires observers to deduce changed item Observer Pattern:  Observer Pattern Implementation Issues How does the subject keep track of its observers? Array, linked list What if an observer wants to observe more than one subject? Have the subject tell the observer who it is via the update interface Who triggers the update? The subject whenever its state changes The observers after they cause one or more state changes Some third party object(s) Make sure the subject updates its state before sending out notifications How much info about the change should the subject send to the observers? Push Model - Lots Pull Model - Very Little Can the observers subscribe to specific events of interest? If so, it's publish-subscribe Can an observer also be a subject? Yes! What if an observer wants to be notified only after several subjects have changed state? Use an intermediary object which acts as a mediator Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers Observer Pattern - Example:  Observer Pattern - Example /** *A subject to observe! *Use The java.util.Observable Class */ public class ConcreteSubject extends Observable { private String name; private float price; public ConcreteSubject(String name, float price) { this.name = name; this.price = price; System.out.println('ConcreteSubject created: ' + name + ' at ' + price); } public String getName() {return name;} public float getPrice() {return price;} public void setName(String name) { this.name = name; setChanged(); notifyObservers(name); } public void setPrice(float price) { this.price = price; setChanged(); notifyObservers(new Float(price)); } } Observer Pattern - Example:  Observer Pattern - Example // An observer of name changes. Use The java.util.Observer Interface public class NameObserver implements Observer { private String name; public NameObserver() { name = null; System.out.println('NameObserver created: Name is ' + name); } public void update(Observable obj, Object arg) { if (arg instanceof String) { name = (String)arg; System.out.println('NameObserver: Name changed to ' + name); } else { System.out.println('NameObserver: Some other change to subject!'); } } } Observer Pattern - Example:  Observer Pattern - Example // An observer of price changes. public class PriceObserver implements Observer { private float price; public PriceObserver() { price = 0; System.out.println('PriceObserver created: Price is ' + price); } public void update(Observable obj, Object arg) { if (arg instanceof Float) { price = ((Float)arg).floatValue(); System.out.println('PriceObserver: Price changed to ' + price); } else { System.out.println('PriceObserver: Some other change to subject!'); } } } Observer Pattern - Example:  Observer Pattern - Example // Test program for ConcreteSubject, NameObserver and PriceObserver public class TestObservers { public static void main(String args[]) { // Create the Subject and Observers. ConcreteSubject s = new ConcreteSubject('Corn Pops', 1.29f); NameObserver nameObs = new NameObserver(); PriceObserver priceObs = new PriceObserver(); // Add those Observers! s.addObserver(nameObs); s.addObserver(priceObs); // Make changes to the Subject. s.setName('Frosted Flakes'); s.setPrice(4.57f); s.setPrice(9.22f); s.setName('Sugar Crispies'); } } Observer Pattern - Example:  Observer Pattern - Example Test program output ConcreteSubject created: Corn Pops at 1.29 NameObserver created: Name is null PriceObserver created: Price is 0.0 PriceObserver: Some other change to subject! NameObserver: Name changed to Frosted Flakes PriceObserver: Price changed to 4.57 NameObserver: Some other change to subject! PriceObserver: Price changed to 9.22 NameObserver: Some other change to subject! PriceObserver: Some other change to subject! NameObserver: Name changed to Sugar Crispies

Add a comment

Related presentations

Related pages

The Quilter's Album of Patchwork Patterns: More Than 4050 ...

The Quilter's Album of Patchwork Patterns: More Than 4050 Pieced Blocks for Quilters: Amazon.de: Jinny Beyer: Fremdsprachige Bücher
Read more

Audio Technica AT4050 Multi Pattern Studio Capacitor ...

Purchase the Audio Technica AT4050 Multi Pattern Studio Capacitor Microphone today and save with free shipping on most orders over one hundred dollars.
Read more


• Dual-diaphragm capsule design maintains precise polar pattern definition across the full frequency range of the microphone
Read more

AT4050 Multi-pattern Condenser Microphone || Audio-Technica US

Comments about Audio-Technica AT4050 Multi-pattern Condenser Microphone: I first began using the AT4050 back in 1997, and nearly 20 years later, it still ...
Read more

The Quilter's Album of Patchwork Patterns: More Than 4050 ...

Providing quilters, researchers, and design enthusiasts with a comprehensive tool for finding, identifying, and drafting more than 4,000 unique patterns ...
Read more

9781933308081: The Quilter's Album of Patchwork Patterns ...

AbeBooks.com: The Quilter's Album of Patchwork Patterns: 4050 Pieced Blocks for Quilters (9781933308081) by Beyer, Jinny and a great selection of similar ...
Read more

Sewing Patterns - Pattern Reviews for Butterick Pattern ...

Pattern Description: Butterick 4050 Pattern Sizing: 16 1/2 ... Pattern alterations or any design changes you made: I did not make the belt or the pockets.
Read more

Audio-Technica AT4050 Multi-Pattern Condenser Microphone ...

The AT4050 Multi-Pattern Condenser Microphone from Audio-Technica features three switchable polar patterns: cardioid, omnidirectional, and figure 8.
Read more

AT4050/LE LIMITED EDITION Multi-pattern Condenser ...

The AT4050/LE’s dual large-diaphragm design provides consistent, ... omnidirectional and figure-of-eight polar pattern settings. ... 4050 anniversary.
Read more