dp unit 2 Creational Patterns
dp unit 2 Creational Patterns
dp unit 2 Creational Patterns
CREATIONAL
PATTERNS
CREATIONAL PATTERNS
Intent:
Provide an interface for creating families of related
or dependent objects without specifying their concrete
classes.
Also Known As: Kit
Motivation: Consider a user interface toolkit that
supports multiple look-and-feel standards, such as Motif
and Presentation Manager.
•We can solve this problem by defining an abstract
WidgetFactory class that declares an interface for
creating each basic kind of widget.
ABSTRACT FACTORY:(Object Creational)
•There's also an abstract class for each kind of widget,
and concrete subclasses implement widgets for
specific look-and-feel standards.
AbstractFactory (WidgetFactory)
o Declares an interface for operations that create abstract product objects.
ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
o Implements the operations to create concrete product objects.
AbstractProduct(Window, ScrollBar)
o Declares an interface for a type of product object.
ConcreteProduct(MotifWindow, MotifScrollBar)
Defines a product object to be created by the corresponding concrete factory by implementing
the AbstractProduct interface.
Client
Uses the interfaces of Abstract Factory and Product classes.
Collaborations:
•Normally a single instance of a Concrete Factory class is created at run-time.
•This concrete factory 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 subclass.
Consequences:
The AbstractFactory pattern has the following benefits sand liabilities:
1. It isolates concrete classes: Helps you control the classes of objects than an
application creates.
2.It makes exchanging product families easy: The classes of a concrete factory
appears only once in an application -i.e., where its instantiated.
3.It promotes consistency among products: An application use objects from only one
family at a time. Abstract Factory makes this easy to enforce.
Here are some useful techniques for implementing the AbstractFactory pattern.
1. Factories as singletons: An application typically needs only one instance
of a concrete factory per product family.
2. Creating the products: Abstract factory only declares an interface for creating
products.
3. Defining extensible factories:. Adding new kind of product requires
changing the Abstract Factory interface and all the classes that depend on it.
Sample Code
// Each concrete factory has a
interface GUIFactory { //corresponding product variant.
Button createButton(); class MacFactory implements GUIFactory {
Checkbox createCheckbox(); Button createButton(){
} return new MacButton() }
Checkbox createCheckbox(){
class WinFactory implements GUIFactory { return new MacCheckbox() }
Button createButton() { }
return new WinButton() }
Checkbox createCheckbox() {
return new WinCheckbox() }
}
KnownUses:
• InterViews uses the"Kit“ suffix to denote AbstractFactory classes. It defines
WidgetKit and DialogKit abstract factories for generating look-and-feel-specific user
interface objects.
• InterViews also includes a LayoutKit that generates different composition objects
depending on the layout desired.
• ET++ uses the Abstract Factory pattern to achieve portability across different
window systems.
RelatedPatterns:
• Abstract Factory classes are often implemented with factory methods (Factory
Method),
Motivation:
•A reader for the RTF document exchange format should be able to
convert RTF to many text formats.
•As the RTF Reader parses the RTF document, it uses the
TextConverter to perform the conversion.
Structure:
Participants:
Builder(TextConverter)
Specifies an abstract interface for creating parts of a Product
object.
Director(RTFReader)
Constructs an object using the Builder interface.
Consequences:
interface Builder { // The concrete builder classes follow the builder interface
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.
AlsoKnown As: Virtual Constructor
Motivation:
Classes delegate responsibility to one of several helper subclasses, and you want to
localize the knowledge of which helper subclass is the delegate.
Structure:
Participants
Product(Document)
Defines the interface of objects the factorymethod creates.
ConcreteProduct (MyDocument)
Implements the Product interface.
Creator(Application)
• Declares the factory method, which returns an object of type Product.
• Define a default implementation of the factory method that returns a
default ConcreteProduct object.
• Calls the factorymethod to create a Product object.
ConcreteCreator (MyApplication)
Overrides the factorymethod to return an instance of a ConcreteProduct.
Consequences
Factory methods eliminate the need to bind application-specific classes into
our code.
A potential disadvantage of factory methods is that clients might have to
subclass the Creator class just to create a Concrete Product object.
2.Parameterized factory methods. The factory method takes a parameter that identifies
the kind of object to create. All objects the factory method creates will share the
Product interface.
4.Using templates to avoid sub classing. Another potential problem with factory
methods is that they might force you to subclass just to create the appropriate Product
objects.
5.Naming conventions. Using naming conventions makes it clear you're using factory
methods.
SAMPLE CODE
It'll provide an abstract Tool class for defining tools like those in the
palette.
•This can reduce the number of classes in the system dramatically. It also
makes it easier to add a new kind of note to the music editor.
Applicability:
•Use the Prototype pattern when a system should be independent of
how its products are created, composed, and represented; and
•When the classes to instantiate are specified at run-time, for
example, by dynamic loading; or
•To avoid building a class hierarchy of factories that parallels the
class hierarchy of products; or
•When instances of a class can have one of only a few different
combinations of state.
Structure
Participants:
Prototype(Graphic)
Declares an interface for cloningitself.
ConcretePrototype (Staff, WholeNote, HalfNote)
Implements an operation for cloning itself.
Client(GraphicTool)
Creates a new object by asking a prototype to clone itself.
Consequences:
It hides the concrete product classes from the client,
Additional benefits of the Prototype pattern are listed below.
•A client will ask the registry for a prototype before cloning it.
3.Initializing clones.
Clients will want to initialize some or all of its internal state to values
of their choosing.
// The clone operation returns one of the Shape subclasses.
// Base prototype. abstract method clone():Shape
abstract class Shape is
field X: int
field Y: int class Rectangle extends Shape is
field color: string field width: int
field height: int
// A regular constructor.
constructor Shape() is constructor Rectangle(source: Rectangle) is
// ... // A parent constructor call is needed to copy private
// fields defined in the parent class.
// The prototype constructor. A fresh object is initialized super(source)
// with values from the existing object. this.width = source.width
constructor Shape(source: Shape) is this.height = source.height
this()
this.X = source.X method clone():Shape is
this.Y = source.Y return new Rectangle(this)
this.color = source.color
Known Uses:
•Perhaps the first example of the Prototype pattern was in Ivan
Sutherland's Sketchpad system.
•Designs that make heavy use of the Composite and Decorator patterns
often can benefit from Prototype as well.
Singleton
Intent:
Ensure a class only has one instance, and provide a global point of access to
it.
Motivation:
It's important for some classes to have exactly one instance.
Examples:
•There should be only one file system and one window manager.
The class can ensure that no other instance can be created, and it can provide a way to
Structure:
Participants:
Singleton
Defines an Instance operation that lets clients access its unique
instance. Instance is a class operation that is responsible for creating its
own unique instance.
Consequences:
The Singleton pattern has several benefits:
1.Controlled access to sole instance. Because the Singleton class
encapsulates its sole instance, it can have strict control over how and when
clients access it.
2.Reduced name space. The Singleton pattern is an improvement
over global variables. It avoids polluting the name space with global
variables that store sole instances.
3.Permits refinement of operations and representation. We can
configure the application with an instance of the class we need at run-time.
1.Permits a variable number of instances. The pattern makes it easy to change your
mind and allow more than one instance of the Singleton class.
Implementation:
Here are implementation issues to consider when using the Singleton pattern:
1.Ensuring a unique instance. The Singleton pattern makes the sole instance a
normal instance of a class, but that class is written so that only one instance can ever be
created by hiding the operation that creates the instance behind a class operation that
guarantees only one instance is created.
2.Registry for Singletons. The main issue is installing its unique instance so that
clients will be able to use it. A more flexible approach uses a registry of singletons. The
Singleton classes can register their singleton instance by name in a well-known registry.
This approach frees Instance from knowing all possible Singleton classes or
instances.
SampleCode:
class Database is
// The field for storing the singleton instance should be
// declared static and private.
private static field instance: Database
class Application is method main() is
// The singleton's constructor should always be private to
// prevent direct construction calls with the `new` Database foo = Database.getInstance()
// operator. foo.query("SELECT ...")
private constructor Database() is // ...
// Some initialization code, such as the actual
// database connection
Database bar = Database.getInstance()
public static method getInstance() is bar.query("SELECT ...")
// Ensure that the instance hasn't yet been // The variable `bar` will contain the same
if (Database.instance == null) then
//object as the variable `foo`.
Database.instance = new Database()
return Database.instance
// Finally, any singleton should define some business logic
// which can be executed on its instance.
public method query(sql) is
// For instance, all database queries of an app go
// through this method. Therefore, you can place
// throttling or caching logic here.
// ...
SampleCode:
class Database is
class Application is method main() is
private static field instance: Database
Database foo = Database.getInstance()
private constructor Database() is
foo.query("SELECT ...")
public static method getInstance() is
// ...
if (Database.instance == null) then
Database bar = Database.getInstance()
Database.instance = new Database()
bar.query("SELECT ...")
return Database.instance
// The variable `bar` will contain the same
public method query(sql) is
//object as the variable `foo`.
// ...
Known Uses:
An example of the Singleton pattern in Smalltalk-80 is the set of changes to
the code, which is ChangeSet current. A more subtle example is the
relationship between classes and their meta classes.
The InterViews user interface toolkit uses the Singleton pattern to access the
unique instance of its Session and WidgetKit classes, among others.
Related Patterns:
Many patterns can be implemented using the Singleton pattern:
AbstractFactory, Builder, and Prototype.
Discussion of Creational Patterns
1.Subclass the class that creates the objects; this corresponds to using
the Factory Method pattern. The main drawback of this approach is that it
can require creating a new subclass just to change the class of the product.
Such changes can cascade.
•Overall, the Prototype pattern is probably the best for the drawing
editor framework, because it only requires implementing a Clone
operation on each Graphics class. That reduces the number of
classes, and Clone can be used for purposes other than pure instantiation.
•Other design patterns require new classes, whereas Factory Method only
requires a new operation.
•Designs that use Abstract Factory, Prototype, or Builder are even more
flexible than those that use Factory Method, but they're also more complex.