Download Design Patterns: Creational, Structural, and Behavioral and more Study notes Computer science in PDF only on Docsity!
Creational structural
and behavioural
design patterns
Week 8 & 9
What is Design Pattern
- Addresses a recurring design problem that arises in specific design situations and presents a solution to it.
- Constitutes a set of rules describing how to accomplish certain tasks in software development
- Focus more on reuse of recurring architectural design themes, while frameworks focus on detailed design and implementation
- Identify and specify abstractions that are above the level of single classes and instances or of components. (Gamma, Johnson, and Vlissides, 1993)
- Helps in improving code quality
Grouping Design Patterns
- Creational patterns create objects for you rather than having you instantiate objects directly. Gives program more flexibility in deciding which objects need to be created for a given case
- Structural patterns help you compose groups of objects into larger structures, such as complex user interfaces or accounting data.
- Behavioral patterns help you define the communication between objects in your system and how the flow is controlled in a complex program. Patterns solve software structural problems like: - Abstraction, - Encapsulation - Information hiding - Separation of concerns - Coupling and cohesion - Separation of interface and implementation - Single point of reference - Divide and conquer
Types of Pattern There are 3 types of pattern ā¦
- Creational : address problems of creating an object in a flexible way. Separate creation, from operation/use.
- Structural : address problems of using O-O constructs like inheritance to organize classes and objects
- Behavioral : address problems of assigning responsibilities to classes. Suggest both static relationships and patterns of communication (use cases) Patterns, Architectures & Frameworks
- There can be confusion between patterns, architectures and frameworks.
- Letās try to distinguish them:
- Architectures model software structure at the highest possible level, and give the overall system view. An architecture can use many different patterns in different components
- Patterns are more like small-scale or local architectures for architectural components or sub-components
- Frameworks are partially completed software systems that may be targeted at a particular type of application. These are tailored by completing the unfinished components. Summary of Differences
- Patterns are more general and abstract than frameworks. A pattern is a description of a solution, not a solution itself.
- A pattern cannot be directly implemented. An implementation is an example of a pattern.
- Patterns are more primitive than frameworks. A framework can employ several patterns.
- Name : meaningful text that reflects the problem, e.g. Bridge, Mediator, Flyweight
- Problem addressed : intent of the pattern, objectives achieved within certain constraints
- Context : circumstances under which it can occur, used to determine applicability
- Forces : constraints or issues that solution must address, forces may conflict!
- Solution : the static and dynamic relationships among the pattern components. Structure, participants, collaboration. Solution must resolve all forces! Pattern: Singleton (Creational) Name: Singleton Problem: How can we guarantee that one and only one instance of a class can be created? Context: In some applications it is important to have exactly one instance of a class, e.g. sales of one company.
Forces: Can make an object globally accessible as a global variable, but this violates encapsulation. Could use class (static) operations and attributes, but polymorphic redefinition is not always possible. Solution: Create a class with a class operation getInstance(). When class is first accessed, this creates relevant object instance and returns object identity to client. On subsequent calls of getInstance(), no new instance is created, but identity of existing object is returned. Singleton Structure Singleton
**- uniqueInstance
- singletonData +getInstance( ) +getSingletonData( ) +singletonOperation( )
- Singleton( )** Object identifier for singleton instance, class scope or static Returns object identifier for unique instance, class-scope or static Private constructor only accessible via getInstance() getInstance( ) { if ( uniqueInstance == null ) { uniqueInstance = new Singleton( ) } return uniqueInstance }
Pattern: FaƧade (Structural) Name: FaƧade Problem: How can we access a large number of classes with a complex internal interaction in a simple but safe way? Solution: Introduce a dedicated interface class that simplifies the view of the class collection. Facade Structure Facade subsystem classes
<<faƧade>> SecurityManager +addAccessRight() +addActor() +addActorRole() +removeActor() AccessRight +addAccessRight() Actor +addActor() +removeActor() +changeSalary() ActorRole +addActorRole() Method not in Facade Pattern Name Comments
- Clients communicate with the subsystem by sending requests to FaƧade which forwards them to the appropriate subsystem object(s).
- Although subsystem objects perform actual work, FaƧade may have to translate its interface to subsystem interfaces.
- Clients that use the FaƧade donāt have to access its subsystem objects directly.
- A pattern for two objects which exist independently but have some coupling. This coupling is placed in its own class.
- Used by e.g. ActionListener in graphics which couples together two graphical objects, e.g. window & button Mediator Structure Mediator ConcreteMediator 1 mediator
Colleague Concrete Colleague Concrete Colleague
- Colleagues send and receive requests from a Mediator object. The mediator implements the cooperative behavior by routing requests between appropriate colleagues. Example: Top-Down Design Mediator File_Selector 1 mediator
Colleague Browser Text_Field My_Application Button
Pattern: Observer (Behavioral) Name: Observer Problem: Define a one-to-many dependency among objects so that when one object changes state, all of its dependents are notified and updated automatically. Solution : MVC, but refined by separating abstract from concrete subjects and observers Observer ConcreteObserver Update() observerState update() Subject ConcreteSubject attach(Observer) detach(Observer) notify() subjectState () getState() setState()
observerState = subject.getState( ) return subjectState for all o in observers { o.update( ) }
- ConcreteSubject notifies its observers whenever a change occurs that could make its observers state inconsistent with its own
- After being informed of change, a ConcreteObserver queries the subject to reconcile its state with subjects.
- Observer object that initiates change request postpones its update until it gets notification from subject. Notify() is not always called by subject. Can be called by an observer, or any other object.
- Pattern is well known, has wide range of variants aConcrete Subject: aConcrete Subject: aConcrete Subject: setState( ) notify( ) update( ) getState( ) update( ) getState( )
Factory Structure AbstractProduct ConcreteProduct AbstractFactory ConcreteFactory FactoryMethod() AnOperation() FactoryMethod() Product = FactoryMethod() return new ConcreteProduct()
- Normally, a single instance of a ConcreteFactory class is created at runtime.
- This creates product objects having a particular implementation.
- To create different product objects, clients should use a different concrete factory.
- AbstractFactory defers creation of product objects to its ConcreteFactory subclasses.
MyClass createObjectOfRequiredClass():RequiredClass Factory design pattern Client RequiredClass Factory Class Model create objects Factory Example
- E.g. create objects of different types
- We can order a Car and get an Aston Martin, MG, Jaguar etc
- We donāt know which factory builds the car, just that they implement CarFactory. Owner has created the actual factory instance.