Design Patterns

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Creational design patterns list?

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 Object Pool- Avoid expensive acquisition and release of resources by recycling objects that are no longer in use Prototype- A fully initialized instance to be copied or cloned Singleton- A class of which only a single instance can exist

What is Behavioral design patterns?

These design patterns are all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects.

Structural design patterns?

In Software Engineering, Structural Design Patterns are Design Patterns that ease the design by identifying a simple way to realize relationships between entities. -- These design patterns are all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.

Facade Design Pattern?

Intent (s) -Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. -Wrap a complicated subsystem with a simpler interface. Problem A segment of the client community needs a simplified interface to the overall functionality of a complex subsystem. Discussion Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that "power users" may need. The Facade object should be a fairly simple advocate or facilitator. It should not become an all-knowing oracle or "god" object.

Structural design patterns list?

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 subsystem Flyweight- A fine-grained instance used for efficient sharing Private Class Data- Restricts accessor/mutator access Proxy- An object representing another object

What Is an AntiPattern?

An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences. The AntiPattern may be the result of a manager or developer not knowing any better, not having sufficient knowledge or experience in solving a particular type of problem, or having applied a perfectly good pattern in the wrong context.

Design Patterns?

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn't a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

what is Creational design patterns?

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.

Composite Design Pattern?

Intent (s) -Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. -Recursive composition -"Directories contain entries, each of which could be a directory." -1-to-many "has a" up the "is a" hierarchy Problem Application needs to manipulate a hierarchical collection of "primitive" and "composite" objects. Processing of a primitive object is handled one way, and processing of a composite object is handled differently. Having to query the "type" of each object before attempting to process it is not desirable. Discussion Define an abstract base class (Component) that specifies the behavior that needs to be exercised uniformly across all primitive and composite objects. Subclass the Primitive and Composite classes off of the Component class. Each Composite object "couples" itself only to the abstract type Component as it manages its "children". Use this pattern whenever you have "composites that contain components, each of which could be a composite". Child management methods [e.g. addChild(), removeChild()] should normally be defined in the Composite class. Unfortunately, the desire to treat Primitives and Composites uniformly requires that these methods be moved to the abstract Component class. See the "Opinions" section below for a discussion of "safety" versus "transparency" issues.

Builder Design Pattern?

intent (c) -Separate the construction of a complex object from its representation so that the same construction process can create different representations. -Parse a complex representation, create one of several targets. problem An application needs to create the elements of a complex aggregate. The specification for the aggregate exists on secondary storage and one of many representations needs to be built in primary storage. Discussion Separate the algorithm for interpreting (i.e. reading and parsing) a stored persistence mechanism (e.g. RTF files) from the algorithm for building and representing one of many target products (e.g. ASCII, TeX, text widget). The focus/distinction is on creating complex aggregates. The "director" invokes "builder" services as it interprets the external format. The "builder" creates part of the complex object each time it is called and maintains all intermediate state. When the product is finished, the client retrieves the result from the "builder". Affords finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the control of the "director".

Behavioral design list?

Chain of responsibility- 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 Null Object- Designed to act as a default value of an object Observer- A way of notifying change to a number of classes State- Alter an object's behavior when its state 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

Singleton Design Pattern?

Intent (c) -Ensure a class has only one instance, and provide a global point of access to it. -Encapsulated "just-in-time initialization" or "initialization on first use". Problem Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary. Discussion Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance. The client calls the accessor function (using the class name and scope resolution operator) whenever a reference to the single instance is required. Singleton should be considered only if all three of the following criteria are satisfied: Ownership of the single instance cannot be reasonably assigned Lazy initialization is desirable Global access is not otherwise provided for If ownership of the single instance, when and how initialization occurs, and global access are not issues, Singleton is not sufficiently interesting. The Singleton pattern can be extended to support access to an application-specific number of instances. The "static member function accessor" approach will not support subclassing of the Singleton class. If subclassing is desired, refer to the discussion in the book. Deleting a Singleton class/instance is a non-trivial design problem. See "To Kill A Singleton" by John Vlissides for a discussion.

State Design Pattern

Intent (b) Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. An object-oriented state machine wrapper + polymorphic wrappee + collaboration Problem A monolithic object's behavior is a function of its state, and it must change its behavior at run-time depending on that state. Or, an application is characterized by large and numerous case statements that vector flow of control based on the state of the application. Discussion The State pattern is a solution to the problem of how to make behavior depend on state. Define a "context" class to present a single interface to the outside world. Define a State abstract base class. Represent the different "states" of the state machine as derived classes of the State base class. Define state-specific behavior in the appropriate State derived classes. Maintain a pointer to the current "state" in the "context" class. To change the state of the state machine, change the current "state" pointer. The State pattern does not specify where the state transitions will be defined. The choices are two: the "context" object, or each individual State derived class. The advantage of the latter option is ease of adding new State derived classes. The disadvantage is each State derived class has knowledge of (coupling to) its siblings, which introduces dependencies between subclasses. A table-driven approach to designing finite state machines does a good job of specifying state transitions, but it is difficult to add actions to accompany the state transitions. The pattern-based approach uses code (instead of data structures) to specify state transitions, but it does a good job of accommodating state transition actions.

Chain of Responsibility

Intent (b) Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. Launch-and-leave requests with a single processing pipeline that contains many possible handlers. An object-oriented linked list with recursive traversal. Problem There is a potentially variable number of "handler" or "processing element" or "node" objects, and a stream of requests that must be handled. Need to efficiently process the requests without hard-wiring handler relationships and precedence, or request-to-handler mappings. Discussion Encapsulate the processing elements inside a "pipeline" abstraction; and have clients "launch and leave" their requests at the entrance to the pipeline. The pattern chains the receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message. The number and type of handler objects isn't known a priori, they can be configured dynamically. The chaining mechanism uses recursive composition to allow an unlimited number of handlers to be linked. Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain. Make sure there exists a "safety net" to "catch" any requests which go unhandled. Do not use Chain of Responsibility when each request is only handled by one handler, or, when the client object knows which service object should handle the request.

Strategy Design Pattern

Intent (b) Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it. Capture the abstraction in an interface, bury implementation details in derived classes. Problem One of the dominant strategies of object-oriented design is the "open-closed principle". Figure demonstrates how this is routinely achieved - encapsulate interface details in a base class, and bury implementation details in derived classes. Clients can then couple themselves to an interface, and not have to experience the upheaval associated with change: no impact when the number of derived classes changes, and no impact when the implementation of a derived class changes. Strategy scheme A generic value of the software community for years has been, "maximize cohesion and minimize coupling". The object-oriented design approach shown in figure is all about minimizing coupling. Since the client is coupled only to an abstraction (i.e. a useful fiction), and not a particular realization of that abstraction, the client could be said to be practicing "abstract coupling" . an object-oriented variant of the more generic exhortation "minimize coupling". A more popular characterization of this "abstract coupling" principle is "Program to an interface, not an implementation". Clients should prefer the "additional level of indirection" that an interface (or an abstract base class) affords. The interface captures the abstraction (i.e. the "useful fiction") the client wants to exercise, and the implementations of that interface are effectively hidden.

Observer Design Pattern

Intent (b) Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy. The "View" part of Model-View-Controller. Problem A large monolithic design does not scale well as new graphing or monitoring requirements are levied. Discussion Define an object that is the "keeper" of the data model and/or business logic (the Subject). Delegate all "view" functionality to decoupled and distinct Observer objects. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject's state that it is responsible for monitoring. This allows the number and "type" of "view" objects to be configured dynamically, instead of being statically specified at compile-time. The protocol described above specifies a "pull" interaction model. Instead of the Subject "pushing" what has changed to all Observers, each Observer is responsible for "pulling" its particular "window of interest" from the Subject. The "push" model compromises reuse, while the "pull" model is less efficient. Issues that are discussed, but left to the discretion of the designer, include: implementing event compression (only sending a single change broadcast after a series of consecutive changes has occurred), having a single Observer monitoring multiple Subjects, and ensuring that a Subject notify its Observers when it is about to go away. The Observer pattern captures the lion's share of the Model-View-Controller architecture that has been a part of the Smalltalk community for years.

Mediator Design Pattern

Intent (b) Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Design an intermediary to decouple many peers. Promote the many-to-many relationships between interacting peers to "full object status". Problem We want to design reusable components, but dependencies between the potentially reusable pieces demonstrates the "spaghetti code" phenomenon (trying to scoop a single serving results in an "all or nothing clump"). Discussion In Unix, permission to access system resources is managed at three levels of granularity: world, group, and owner. A group is a collection of users intended to model some functional affiliation. Each user on the system can be a member of one or more groups, and each group can have zero or more users assigned to it. Next figure shows three users that are assigned to all three groups. Mediator example If we were to model this in software, we could decide to have User objects coupled to Group objects, and Group objects coupled to User objects. Then when changes occur, both classes and all their instances would be affected. An alternate approach would be to introduce "an additional level of indirection" - take the mapping of users to groups and groups to users, and make it an abstraction unto itself. This offers several advantages: Users and Groups are decoupled from one another, many mappings can easily be maintained and manipulated simultaneously, and the mapping abstraction can be extended in the future by defining derived classes. Mediator example Partitioning a system into many objects generally enhances reusability, but proliferating interconnections between those objects tend to reduce it again. The mediator object: encapsulates all interconnections, acts as the hub of communication, is responsible for controlling and coordinating the interactions of its clients, and promotes loose coupling by keeping objects from referring to each other explicitly. The Mediator pattern promotes a "many-to-many relationship network" to "full object status". Modelling the inter-relationships with an object enhances encapsulation, and allows the behavior of those inter-relationships to be modified or extended through subclassing. An example where Mediator is useful is the design of a user and group capability in an operating system. A group can have zero or more users, and, a user can be a member of zero or more groups. The Mediator pattern provides a flexible and non-invasive way to associate and manage users and groups.

Template Method Design Pattern

Intent (b) Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Base class declares algorithm 'placeholders', and derived classes implement the placeholders. Problem Two different components have significant similarities, but demonstrate no reuse of common interface or implementation. If a change common to both components becomes necessary, duplicate effort must be expended. Discussion The component designer decides which steps of an algorithm are invariant (or standard), and which are variant (or customizable). The invariant steps are implemented in an abstract base class, while the variant steps are either given a default implementation, or no implementation at all. The variant steps represent "hooks", or "placeholders", that can, or must, be supplied by the component's client in a concrete derived class. The component designer mandates the required steps of an algorithm, and the ordering of the steps, but allows the component client to extend or replace some number of these steps. Template Method is used prominently in frameworks. Each framework implements the invariant pieces of a domain's architecture, and defines "placeholders" for all necessary or interesting client customization options. In so doing, the framework becomes the "center of the universe", and the client customizations are simply "the third rock from the sun". This inverted control structure has been affectionately labelled "the Hollywood principle" - "don't call us, we'll call you".

Command Design Pattern

Intent (b) Encapsulate a request as an object, thereby letting you parametrize clients with different requests, queue or log requests, and support undoable operations. Promote "invocation of a method on an object" to full object status An object-oriented callback Problem Need to issue requests to objects without knowing anything about the operation being requested or the receiver of the request. Discussion Command decouples the object that invokes the operation from the one that knows how to perform it. To achieve this separation, the designer creates an abstract base class that maps a receiver (an object) with an action (a pointer to a member function). The base class contains an execute() method that simply calls the action on the receiver. All clients of Command objects treat each object as a "black box" by simply invoking the object's virtual execute() method whenever the client requires the object's "service". A Command class holds some subset of the following: an object, a method to be applied to the object, and the arguments to be passed when the method is applied. The Command's "execute" method then causes the pieces to come together. Sequences of Command objects can be assembled into composite (or macro) commands.

Interpreter Design Pattern

Intent (b) Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design. Problem A class of problems occurs repeatedly in a well-defined and well-understood domain. If the domain were characterized with a "language", then problems could be easily solved with an interpretation "engine". Discussion The Interpreter pattern discusses: defining a domain language (i.e. problem characterization) as a simple language grammar, representing domain rules as language sentences, and interpreting these sentences to solve the problem. The pattern uses a class to represent each grammar rule. And since grammars are usually hierarchical in structure, an inheritance hierarchy of rule classes maps nicely. An abstract base class specifies the method interpret(). Each concrete subclass implements interpret() by accepting (as an argument) the current state of the language stream, and adding its contribution to the problem solving process.

Iterator Design Pattern

Intent (b) Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation. The C++ and Java standard library abstraction that makes it possible to decouple collection classes and algorithms. Promote to "full object status" the traversal of a collection. Polymorphic traversal Problem Need to "abstract" the traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each transparently. Discussion "An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don't want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you'll require. You might also need to have more than one traversal pending on the same list." And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable. The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol. The Iterator abstraction is fundamental to an emerging technology called "generic programming". This strategy seeks to explicitly separate the notion of "algorithm" from that of "data structure". The motivation is to: promote component-based development, boost productivity, and reduce configuration management. As an example, if you wanted to support four data structures (array, binary tree, linked list, and hash table) and three algorithms (sort, find, and merge), a traditional approach would require four times three permutations to develop and maintain. Whereas, a generic programming approach would only require four plus three configuration items.

Visitor Design Pattern

Intent (b) Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The classic technique for recovering lost type information. Do the right thing based on the type of two objects. Double dispatch Problem Many distinct and unrelated operations need to be performed on node objects in a heterogeneous aggregate structure. You want to avoid "polluting" the node classes with these operations. And, you don't want to have to query the type of each node and cast the pointer to the correct type before performing the desired operation. Discussion Visitor's primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of "element" objects. The approach encourages designing lightweight Element classes - because processing functionality is removed from their list of responsibilities. New functionality can easily be added to the original inheritance hierarchy by creating a new Visitor subclass. Visitor implements "double dispatch". OO messages routinely manifest "single dispatch" - the operation that is executed depends on: the name of the request, and the type of the receiver. In "double dispatch", the operation executed depends on: the name of the request, and the type of TWO receivers (the type of the Visitor and the type of the element it visits). The implementation proceeds as follows. Create a Visitor class hierarchy that defines a pure virtual visit() method in the abstract base class for each concrete derived class in the aggregate node hierarchy. Each visit() method accepts a single argument - a pointer or reference to an original Element derived class. Each operation to be supported is modelled with a concrete derived class of the Visitor hierarchy. The visit() methods declared in the Visitor base class are now defined in each derived subclass by allocating the "type query and cast" code in the original implementation to the appropriate overloaded visit() method. Add a single pure virtual accept() method to the base class of the Element hierarchy. accept() is defined to receive a single argument - a pointer or reference to the abstract base class of the Visitor hierarchy. Each concrete derived class of the Element hierarchy implements the accept() method by simply calling the visit() method on the concrete derived instance of the Visitor hierarchy that it was passed, passing its "this" pointer as the sole argument. Everything for "elements" and "visitors" is now set-up. When the client needs an operation to be performed, (s)he creates an instance of the Visitor object, calls the accept() method on each Element object, and passes the Visitor object. The accept() method causes flow of control to find the correct Element subclass. Then when the visit() method is invoked, flow of control is vectored to the correct Visitor subclass. accept() dispatch plus visit() dispatch equals double dispatch. The Visitor pattern makes adding new operations (or utilities) easy - simply add a new Visitor derived class. But, if the subclasses in the aggregate node hierarchy are not stable, keeping the Visitor subclasses in sync requires a prohibitive amount of effort. An acknowledged objection to the Visitor pattern is that is represents a regression to functional decomposition - separate the algorithms from the data structures. While this is a legitimate interpretation, perhaps a better perspective/rationale is the goal of promoting non-traditional behavior to full object status.

Null Object Design Pattern

Intent (b) The intent of a Null Object is to encapsulate the absence of an object by providing a substitutable alternative that offers suitable default do nothing behavior. In short, a design where "nothing will come of nothing" Use the Null Object pattern when an object requires a collaborator. The Null Object pattern does not introduce this collaboration--it makes use of a collaboration that already exists some collaborator instances should do nothing you want to abstract the handling of null away from the client Problem Given that an object reference may be optionally null, and that the result of a null check is to do nothing or use some default value, how can the absence of an object — the presence of a null reference — be treated transparently? Discussion Sometimes a class that requires a collaborator does not need the collaborator to do anything. However, the class wishes to treat a collaborator that does nothing the same way it treats one that actually provides behavior. Consider for example a simple screen saver which displays balls that move about the screen and have special color effects. This is easily achieved by creating a Ball class to represent the balls and using a Strategy pattern to control the ball's motion and another Strategy pattern to control the ball's color. It would then be trivial to write strategies for many different types of motion and color effects and create balls with any combination of those. However, to start with you want to create the simplest strategies possible to make sure everything is working. And these strategies could also be useful later since you want as strategies as possible strategies. Null Object scheme Now, the simplest strategy would be no strategy. That is do nothing, don't move and don't change color. However, the Strategy pattern requires the ball to have objects which implement the strategy interfaces. This is where the Null Object pattern becomes useful. Simply implement a NullMovementStrategy which doesn't move the ball and a NullColorStrategy which doesn't change the ball's color. Both of these can probably be implemented with essentially no code. All the methods in these classes do "nothing". They are perfect examples of the Null Object Pattern. The key to the Null Object pattern is an abstract class that defines the interface for all objects of this type. The Null Object is implemented as a subclass of this abstract class. Because it conforms to the abstract class' interface, it can be used any place this type of object is needed. As compared to using a special "null" value which doesn't actually implement the abstract interface and which must constantly be checked for with special code in any object which uses the abstract interface. It is sometimes thought that Null Objects are over simple and "stupid" but in truth a Null Object always knows exactly what needs to be done without interacting with any other objects. So in truth it is very "smart."

Memento Design Pattern

Intent (b) Without violating encapsulation, capture and externalize an object's internal state so that the object can be returned to this state later. A magic cookie that encapsulates a "check point" capability. Promote undo or rollback to full object status. Problem Need to restore an object back to its previous state (e.g. "undo" or "rollback" operations). Discussion The client requests a Memento from the source object when it needs to checkpoint the source object's state. The source object initializes the Memento with a characterization of its state. The client is the "care-taker" of the Memento, but only the source object can store and retrieve information from the Memento (the Memento is "opaque" to the client and all other objects). If the client subsequently needs to "rollback" the source object's state, it hands the Memento back to the source object for reinstatement. An unlimited "undo" and "redo" capability can be readily implemented with a stack of Command objects and a stack of Memento objects. The Memento design pattern defines three distinct roles: Originator - the object that knows how to save itself. Caretaker - the object that knows why and when the Originator needs to save and restore itself. Memento - the lock box that is written and read by the Originator, and shepherded by the Caretaker.

Factory Method Design Pattern?

Intent (c) -Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. -Defining a "virtual" constructor. -The new operator considered harmful. problem A framework needs to standardize the architectural model for a range of applications, but allow for individual applications to define their own domain objects and provide for their instantiation. Discussion Factory Method is to creating objects as Template Method is to implementing an algorithm. A superclass specifies all standard and generic behavior (using pure virtual "placeholders" for creation steps), and then delegates the creation details to subclasses that are supplied by the client. Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation. People often use Factory Method as the standard way to create objects; but it isn't necessary if: the class that's instantiated never changes, or instantiation takes place in an operation that subclasses can easily override (such as an initialization operation). Factory Method is similar to Abstract Factory but without the emphasis on families. Factory Methods are routinely specified by an architectural framework, and then implemented by the user of the framework.

Abstract Factory Design Pattern?

Intent (c) -Provide an interface for creating families of related or dependent objects without specifying their concrete classes. -A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products". -The new operator considered harmful. Problem If an application is to be portable, it needs to encapsulate platform dependencies. These "platforms" might include: windowing system, operating system, database, etc. Too often, this encapsulation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code. Discussion Provide a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The "factory" object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them. This mechanism makes exchanging product families easy because the specific class of the factory object appears only once in the application - where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory. Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.

Prototype Design Pattern?

Intent (c) -Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. -Co-opt one instance of a class for use as a breeder of all future instances. -The new operator considered harmful. Problem Application "hard wires" the class of object to create in each "new" expression. Discussion Declare an abstract base class that specifies a pure virtual "clone" method, and, maintains a dictionary of all "cloneable" concrete derived classes. Any class that needs a "polymorphic constructor" capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation. The client then, instead of writing code that invokes the "new" operator on a hard-wired class name, calls a "clone" operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.

Object Pool Design Pattern?

Intent (c) Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low. problem Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created. It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class. Discussion The Object Pool lets others "check out" objects from its pool, when those objects are no longer needed by their processes, they are returned to the pool in order to be reused. However, we don't want a process to have to wait for a particular object to be released, so the Object Pool also instantiates new objects as they are required, but must also implement a facility to clean up unused objects periodically.

Private Class Data?

Intent (s) -Control write access to class attributes -Separate data from methods that use it -Encapsulate class data initialization -Providing new type of final - final after constructor Problem A class may expose its attributes (class variables) to manipulation when manipulation is no longer desirable, e.g. after construction. Using the private class data design pattern prevents that undesirable manipulation. A class may have one-time mutable attributes that cannot be declared final. Using this design pattern allows one-time setting of those class attributes. The motivation for this design pattern comes from the design goal of protecting class state by minimizing the visibility of its attributes (data). Discussion The private class data design pattern seeks to reduce exposure of attributes by limiting their visibility. It reduces the number of class attributes by encapsulating them in single Data object. It allows the class designer to remove write privilege of attributes that are intended to be set only during construction, even from methods of the target class.

Adapter Design Pattern?

Intent (s) -Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. -Wrap an existing class with a new interface. -Impedance match an old component to a new system Problem An "off the shelf" component offers compelling functionality that you would like to reuse, but its "view of the world" is not compatible with the philosophy and architecture of the system currently being developed. Discussion Reuse has always been painful and elusive. One reason has been the tribulation of designing something new, while reusing something old. There is always something not quite right between the old and the new. It may be physical dimensions or misalignment. It may be timing or synchronization. It may be unfortunate assumptions or competing standards. It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall outlet - some kind of adapter or intermediary is necessary. Adapter real example Adapter is about creating an intermediary abstraction that translates, or maps, the old component to the new system. Clients call methods on the Adapter object which redirects them into calls to the legacy component. This strategy can be implemented either with inheritance or with aggregation. Adapter functions as a wrapper or modifier of an existing class. It provides a different or translated view of that class.

Bridge Design Pattern?

Intent (s) -Decouple an abstraction from its implementation so that the two can vary independently. -Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. -Beyond encapsulation, to insulation Problem "Hardening of the software arteries" has occurred by using subclassing of an abstract base class to provide alternative implementations. This locks in compile-time binding between interface and implementation. The abstraction and implementation cannot be independently extended or composed. Discussion Decompose the component's interface and implementation into orthogonal class hierarchies. The interface class contains a pointer to the abstract implementation class. This pointer is initialized with an instance of a concrete implementation class, but all subsequent interaction from the interface class to the implementation class is limited to the abstraction maintained in the implementation base class. The client interacts with the interface class, and it in turn "delegates" all requests to the implementation class. The interface object is the "handle" known and used by the client; while the implementation object, or "body", is safely encapsulated to ensure that it may continue to evolve, or be entirely replaced (or shared at run-time. Use the Bridge pattern when: you want run-time binding of the implementation, you have a proliferation of classes resulting from a coupled interface and numerous implementations, you want to share an implementation among multiple objects, you need to map orthogonal class hierarchies. Consequences include: decoupling the object's interface, improved extensibility (you can extend (i.e. subclass) the abstraction and implementation hierarchies independently), hiding details from clients. Bridge is a synonym for the "handle/body" idiom. This is a design mechanism that encapsulates an implementation class inside of an interface class. The former is the body, and the latter is the handle. The handle is viewed by the user as the actual class, but the work is done in the body. "The handle/body class idiom may be used to decompose a complex abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a single resource by multiple classes that control access to it (e.g. reference counting)."

Flyweight Design Pattern ?

Intent (s) -Use sharing to support large numbers of fine-grained objects efficiently. -The Motif GUI strategy of replacing heavy-weight widgets with light-weight gadgets. Problem Designing objects down to the lowest levels of system "granularity" provides optimal flexibility, but can be unacceptably expensive in terms of performance and memory usage. Discussion The Flyweight pattern describes how to share objects to allow their use at fine granularity without prohibitive cost. Each "flyweight" object is divided into two pieces: the state-dependent (extrinsic) part, and the state-independent (intrinsic) part. Intrinsic state is stored (shared) in the Flyweight object. Extrinsic state is stored or computed by client objects, and passed to the Flyweight when its operations are invoked. An illustration of this approach would be Motif widgets that have been re-engineered as light-weight gadgets. Whereas widgets are "intelligent" enough to stand on their own; gadgets exist in a dependent relationship with their parent layout manager widget. Each layout manager provides context-dependent event handling, real estate management, and resource services to its flyweight gadgets, and each gadget is only responsible for context-independent state and behavior.

Proxy Design Pattern?

Intent (s) Provide a surrogate or placeholder for another object to control access to it. Use an extra level of indirection to support distributed, controlled, or intelligent access. Add a wrapper and delegation to protect the real component from undue complexity. Problem You need to support resource-hungry objects, and you do not want to instantiate such objects unless and until they are actually requested by the client. Discussion Design a surrogate, or proxy, object that: instantiates the real object the first time the client makes a request of the proxy, remembers the identity of this real object, and forwards the instigating request to this real object. Then all subsequent requests are simply forwarded directly to the encapsulated real object. There are four common situations in which the Proxy pattern is applicable. A virtual proxy is a placeholder for "expensive to create" objects. The real object is only created when a client first requests/accesses the object. A remote proxy provides a local representative for an object that resides in a different address space. This is what the "stub" code in RPC and CORBA provides. A protective proxy controls access to a sensitive master object. The "surrogate" object checks that the caller has the access permissions required prior to forwarding the request. A smart proxy interposes additional actions when an object is accessed. Typical uses include: Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer), Loading a persistent object into memory when it's first referenced, Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Decorator Design Pattern?

Intent (s) -Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. -Client-specified embellishment of a core object by recursively wrapping it. -Wrapping a gift, putting it in a box, and wrapping the box. Problem You want to add behavior or state to individual objects at run-time. Inheritance is not feasible because it is static and applies to an entire class. Discussion Suppose you are working on a user interface toolkit and you wish to support adding borders and scroll bars to windows. You could define an inheritance hierarchy like ... Decorator scheme But the Decorator pattern suggests giving the client the ability to specify whatever combination of "features" is desired. Widget* aWidget = new BorderDecorator( new HorizontalScrollBarDecorator( new VerticalScrollBarDecorator( new Window( 80, 24 )))); aWidget->draw(); This flexibility can be achieved with the following design Decorator scheme Another example of cascading (or chaining) features together to produce a custom object might look like ... Stream* aStream = new CompressingStream( new ASCII7Stream( new FileStream("fileName.dat"))); aStream->putString( "Hello world" ); The solution to this class of problems involves encapsulating the original object inside an abstract wrapper interface. Both the decorator objects and the core object inherit from this abstract interface. The interface uses recursive composition to allow an unlimited number of decorator "layers" to be added to each core object. Note that this pattern allows responsibilities to be added to an object, not methods to an object's interface. The interface presented to the client must remain constant as successive layers are specified. Also note that the core object's identity has now been "hidden" inside of a decorator object. Trying to access the core object directly is now a problem.


Kaugnay na mga set ng pag-aaral

CH. 21 - THE MODERN WORLD: 1800-1945

View Set

NUR 414 quiz questions throughout semester

View Set

Another Time Another Place Vocab and Questions

View Set

CHAP 8: Earthquakes + Earth's Interior *

View Set

California Real Estate Principles: Ch. 11

View Set

Chapter 45 Pathophysiology NCLEX-Style Review Questions

View Set