• No results found

Design Patterns Reference Guide

N/A
N/A
Protected

Academic year: 2021

Share "Design Patterns Reference Guide"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

Design Patterns Reference Guide

Explained

Creational Patterns

Pattern

Definition

Participants

UML Class Diagram

Frequency of Usage, Benefits and

Usage

Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes. AbstractFactory

declares an interface for operations that create abstract products

ConcreteFactory

implements the operations to create concrete product objects

AbstractProduct

declares an interface for a type of product object

Product

defines a product object to be created by the corresponding concrete factory implements the AbstractProduct interface Client

uses interfaces declared by AbstractFactory and AbstractProduct classes

High

Benefits

- Isolates concrete classes

- Allows to change product family easily Promotes consistency among products

Usage

- When the system needs to be independent of how its products are created composed and represented. - When the system needs to be configured with one of multiple families of products.

- When a family of products need to be used together and this constraint needs to be enforced.

- -When you need to provide a library of products, expose their interfaces not the implementation.

(2)

Factory Method

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Product

defines the interface of objects the factory method creates

ConcreteProduct

implements the Product interface

Creator

declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default

ConcreteProduct object. may call the factory method to create a Product object.

ConcreteCreator

overrides the factory method to return an instance of a

ConcreteProduct.

High

Benefits

Eliminates the needs to bind application classes into your code. The code deals woth interfaces so it can work with any classes that implement a certain interface.

Enables the subclasses to provide an extended version of an object, because creating an object inside a class is more flexible than creating an object directly in the client.

Usage

When a class cannot anticipate the class of objects it must create.

When a class wants its subclasses to specify the objects it creates.

Classes delegate responsability to one of several helper subclasses, and you want to localize the knowledge of which helper subclasses is the delegate.

Singleton Ensure a class has only one instance and provide a global point of access to it.

Singleton

defines an Instance operation that lets clients access its unique instance. Instance is a class operation.

responsible for creating and maintaining its own unique instance.

medium high

Benefits

Controlled access to unique instance. Reduced name space.

Allows refinement of operations and representations. Permits a variable number of instances.

More flexible than class operations.

Usage

When there must be only one instance of a class.

Structural Patterns

Pattern

Definition

Participants

UML Class Diagram

Frequency of Usage, Benefits and

(3)

Adapter

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces Target

defines the domain-specific interface that Client uses.

Adapter

adapts the interface Adaptee to the Target interface.

Adaptee

defines an existing interface that needs adapting.

Client

collaborates with objects conforming to the Target interface.

medium high Benefits

Allow two or more incompatible objects to communicate and interact.

Improves reusability of older functionality.

Usage

When you want to use an existing class, and its interface does not match the interface you need. When you want to create a reusable class that cooperates with unrelated or onforeseen classes, classes that don't necesarily have compatible interfaces.

When you want to use an object in an environment that expects an interface that is diferent from the object's interface.

When you must ensure interface translation among multiple sources.

Composit

e

Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. Component

 declares the interface for objects in the composition.  implements default

behavior for the interface common to all classes, as appropriate.

 declares an interface for accessing and managing its child components.

 (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.

Leaf

 represents leaf objects in the composition. A leaf has

medium high

Benefits

Define class hierarchies consisting of primitive objects and composite objects.

Makes it easier to add new kind of components. Provides flexibility of structure and manageable interface.

Usage

When you want to represent the whole hierarchy or a part of the hierarchy of objects.

When you want clients to be able to ignore the differences between compositions of objects and individual objects.

When the structure can have any level of complexity andis dynamic.

(4)

no children.  defines behavior for

primitive objects in the composition.

Composite

 defines behavior for components having children.

 stores child components.  implements child-related

operations in the Component interface.

Client

 manipulates objects in the composition through the Component interface.

Decorato

r

Attach additional responsibilitie s to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Component

defines the interface for

objects that can have

responsibilities added to

them dynamically.

ConcreteComponent

defines an object to which

additional responsibilities

can be attached.

Decorator

maintains a reference to a

Component object and

defines an interface that

conforms to Component's

interface.

ConcreteDecorator

adds responsibilities to the

Medium

Benefits

More flexibility than static inheritance.

Avoids feature-laedn classes high up in the hierarchy. Simplifies coding because you write a series of classes each targeted at a specific part of the functionality rather than coding all behavior into the object.

Enhances the object's extensibility because you make changes by coding new classes.

Usage

When you want to add responsibilities to individual objects dinamically and transparently, without affecting other objects.

When you want to add responsibilities to the object that you might want to change in the future. When extension by static subclassing is impractical.

(5)

component.

Facade

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

Facade

knows which subsystem

classes are responsible for

a request.

delegates client requests to

appropriate subsystem

objects.

Subsystem classes

implement subsystem

functionality.

handle work assigned by

the Facade object.

have no knowledge of the

facade and keep no

reference to it.

High

Benefits

Provides a simple interface to a complex system without reducing the functionality provided by the system.

Shields clients from complexity of subsystem components.

Promotes weak coupling between the subsystem and its clients.

Reduces coupling between subsystems if every subsystem uses its own facade pattern.

Translates client requests to the subsystems that can fulfill those requests.

Usage

When you want to provide a simple interface to a complex subsystem.

When there are many dependencies between clients and the implementation classes of an abstraction. When you want to layer your subsystems.

(6)

Proxy

Provide a surrogate or placeholder for another object to control access to it.

Proxy

maintains a reference

that lets the proxy

access the real subject.

Proxy may refer to a

Subject if the

RealSubject and

Subject interfaces are

the same.

provides an interface

identical to Subject's

so that a proxy can be

substituted for for the

real subject.

controls access to the

real subject and may

be responsible for

creating and deleting

it.

other responsibilites

depend on the kind of

proxy:

remote proxies are

responsible for

encoding a request and

its arguments and for

sending the encoded

request to the real

subject in a different

address space.

medium high

Benefits

A remote proxy can hide the fact that an object resides in a different address space.

A virtual proxy can perform optimizations such as creating an object on demand.

both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.

Usage

when you need a more versatile or sophisticated reference to an object than a simple pointer

.

(7)

virtual proxies may

cache additional

information about the

real subject so that

they can postpone

accessing it. For

example, the

ImageProxy from the

Motivation caches the

real images's extent.

protection proxies

check that the caller

has the access

permissions required

to perform a request.

Subject

defines the common

interface for RealSubject

and Proxy so that a Proxy

can be used anywhere a

RealSubject is expected.

RealSubject

defines the real object that

the proxy represents.

Behavioral Patterns

(8)

Command Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Command

declares an interface for

executing an operation

ConcreteCommand

defines a binding between

a Receiver object and an

action

implements Execute by

invoking the

corresponding operation(s)

on Receiver

Client

creates a

ConcreteCommand object

and sets its receiver

Invoker

asks the command to carry

out the request

Receiver

knows how to perform the

operations associated with

carrying out the request.

(9)

Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation .

Iterator

defines an interface for

accessing and traversing

elements.

ConcreteIterator

implements the Iterator

interface.

keeps track of the current

position in the traversal of

the aggregate.

Aggregate

defines an interface for

creating an Iterator object

ConcreteAggregate

implements the Iterator

creation interface to return

an instance of the proper

ConcreteIterator

high

Observer

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Subject

knows its observers. Any

number of Observer

objects may observe a

subject

provides an interface for

attaching and detaching

Observer objects.

ConcreteSubject

stores state of interest to

ConcreteObserver

sends a notification to its

observers when its state

(10)

changes

Observer

defines an updating

interface for objects that

should be notified of

changes in a subject.

ConcreteObserver

maintains a reference to a

ConcreteSubject object

stores state that should

stay consistent with the

subject's

implements the Observer

updating interface to keep

its state consistent with the

subject's

State

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

Context

defines the interface of

interest to clients

maintains an instance of a

ConcreteState subclass

that defines the current

state.

State

defines an interface for

encapsulating the behavior

associated with a

particular state of the

Context.

Concrete State

each subclass implements

(11)

a behavior associated with

a state of Context

Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeab le. Strategy lets the algorithm vary independently from clients that use it.

Strategy

declares an interface

common to all supported

algorithms. Context uses

this interface to call the

algorithm defined by a

ConcreteStrategy

ConcreteStrategy

implements the algorithm

using the Strategy

interface

Context

is configured with a

ConcreteStrategy object

maintains a reference to a

Strategy object

may define an interface

that lets Strategy access its

data.

(12)

Template

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

AbstractClass

defines abstract

primitive operations

that concrete

subclasses define to

implement steps of an

algorithm

implements a template

method defining the

skeleton of an

algorithm. The

template method calls

primitive operations as

well as operations

defined in

AbstractClass or those

of other objects.

ConcreteClass

implements the

primitive operations to

carry out

subclass-specific steps of the

algorithm

(13)

Summary

Creational Patterns

Abstract Factory

Creates an instance of several families of classes

Builder Separates object construction from its representation

Factory Method

Creates an instance of several derived classes

Prototype A fully initialized instance to be copied or cloned

Singleton A class of which only a single instance can exist

Structural Patterns

Adapter Match interfaces of different classes Bridge Separates an object’s interface from its

implementation

Composite A tree structure of simple and composite objects

Decorator Add responsibilities to objects dynamically Facade A single class that represents an entire

(14)

subsystem

Flyweight A fine-grained instance used for efficient sharing

Proxy An object representing another object Behavioral Patterns

Chain of Resp.

A way of passing a request between a chain of objects

Command Encapsulate a command request as an object

Interpreter A way to include language elements in a program

Iterator Sequentially access the elements of a collection

Mediator Defines simplified communication between classes

Memento Capture and restore an object's internal state

Observer A way of notifying change to a number of classes

(15)

changes

Strategy Encapsulates an algorithm inside a class Template

Method

Defer the exact steps of an algorithm to a subclass

Visitor Defines a new operation to a class without change

OO Basics

Abstraction

Encapsulation

Polymorphism

Inheritance

(16)

OO Design Principles

Encapsulate what varies.

Favor composition over inheritance.

Program to interfaces, not implementations.

Strive for loosely coupled designs between objects that interact.

Classes should be open for extension but closed for modification.

Depend on abstractions. Do not depend on concrete classes.

Only talk to your friends.

Don’t call us, we’ll call you.

A class should have only one reason to change.

References:

Head First Design Patterns –

http://www.javainterview.com/design_patterns_interview_questions.html

http://www.java-interview.com/design_patterns_interview_questions.html

http://www.apwebco.com/gofpatterns/

References

Related documents

When the input data is a file (<IN1>), the output data can consist of two parts: one is the same output as generated by <OUT1>, the other is the original file

Four different ways soft opt consent interest pitfalls and conditions for example where possible sale or text has given clear and potentially apply to consent was the time.. Will be

We launched our management division in 1999 and have since operated and maximized profitability for an impressive portfolio of hotels and residential properties on behalf of

By using Zoom Away by Tim Wynne-Jones, the works of Michael Kusugak, The Inukshuk Book , the two stories about polar bears, and the Nunavut workbook, your students will know all

alternatives KS tests of a PP, in Kim and Whitt [2014b ] we let the null hypothesis in the base case be a rate- 1 Poisson process observed over the time interval [0 , 200] , so that

Applications shall include plans clearly delineating the location of the temporary equipment; routing and sizing of utility lines to power and/or fuel the equipment and

Heat creates stress, affects ductility and toughness Effects of previous heat treating are lost around the weld If done properly usually stronger than the base metal Can effect

Zbog toga se dogaĊaji odvijaju protiv oĉekivanja onako kako odredi Bog, kao što je u borbi s gusarima, koja se gotovo nikome nije svidjela, ishod bila radosna pobjeda, a u ovoj,