0% found this document useful (0 votes)
10 views34 pages

Understanding Design Patterns in OOP

The document provides an overview of design patterns, particularly focusing on creational patterns such as Factory and Abstract Factory. It explains the essential elements of design patterns, their purposes, and how they can enhance flexibility and maintainability in object-oriented design. Various examples illustrate the application of these patterns in real-world scenarios, such as car insurance management and home sales inquiry systems.

Uploaded by

2200002438
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views34 pages

Understanding Design Patterns in OOP

The document provides an overview of design patterns, particularly focusing on creational patterns such as Factory and Abstract Factory. It explains the essential elements of design patterns, their purposes, and how they can enhance flexibility and maintainability in object-oriented design. Various examples illustrate the application of these patterns in real-world scenarios, such as car insurance management and home sales inquiry systems.

Uploaded by

2200002438
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DESIGN

PATTERN
Lecture 5
Design Pattern

• What is design pattern?


• Christopher Alexander says,“Each pattern describes a problem
which occurs over and over again in our environment, and then
describe the core of the solution to that problem, in such a way that
you can use the solution a million times over, without ever doing it
the same way twice”.
• Even though Alexander was talking about patterns in buildings and
towns, what he says is true about object-oriented design patterns.
Design Pattern

• What is design pattern?


In general, a pattern has four essential elements:
1. The pattern name is s handle we can use to describe a design
problem, its solutions, and consequences in a word or two.
2. The problem describes when to apply the pattern. It explains the
problems and its context.
3. The solution describes the elements that make up the design,
their relationships, responsibilities, and collaborations.
4. The consequences are the results and trade-off of applying the
pattern.
Design Pattern
Purpose Design pattern

Abstract Factory

Builder

Creational Factory Method

Prototype

Singleton

Adapter

Bridge

Composite

Structure Decorator

Façade

Flyweigh

Proxy
Design Pattern
Purpose Design pattern

Chain of Responsibility

Command

Interpreter

Iterator

Mediator

Memento
Behavioral
Observer

State

Strategy

Template Method

Visitor
Creational pattern
Creational Pattern—Introduction
• The creation of an object

Swimming
Villa object Garden
pool

Billing

Apartment
Room Balcony
object
Creational Pattern—Introduction
• The creation of an object
if ( [Link] == “House” )
House ob = new House();
[Link] ([Link]);
[Link] ([Link]);
[Link] ([Link]);

if ( [Link] == “Cando” )
Cando ob = new Cando();
[Link] ([Link]);
[Link] ([Link]);
[Link] ([Link]);

[Link] ();
Creational Pattern—Overview
• Motivation
− In object-oriented programming, when writing code that creates objects,
you often need to set up many conditional statements to determine
under what conditions, when, and how to create objects of a certain
class. Therefore, it is necessary to delegate the responsibility of creating
an object to a particular class.
• Aims
− The purpose is to increase flexibility in which objects are created, who is
responsible for creating the object, how to create the object, and when
to create the object.
• Content
− The Creational software design pattern is a design pattern that addresses
the object creation mechanism.
Creational pattern
Factory and Abstract Factory
Introduction
• Suppose you want to design a car insurance management program. Car
insurance is divided into many types of insurance, such as Body Injur,
Collision, Personal Injur, Property, and Com. If an application knows exactly
what it needs, it can directly initialize a subclass of the class structure from
the client class's main method and call the functionality provided by that
class. For example, when it is known exactly that the class to be initialized is
Body Injur, the case is invoked by the auto insurance management program
as shown in Figure 1.

Figure1 Knowing exactly the class to initialize is BodyInjure


Introduction
• Usually an application only knows that it needs to access a class in a class
hierarchy, but does not know which class it needs to access. In this case, the
application needs to implement the selection criteria for selecting the
appropriate class from a class hierarchy, as shown in Figure 2.

Figure2 Do not know which class to initialize


Introduction
• In the main method main() shown in FIG. 2, directly selecting which of the
first class methods using a conditional statement will make the program
messy and reduce the readability of the program. An effective improvement
is to write a separate method createObj() in the ClientGUI class to create an
object. This method encapsulates all the different conditions for creating an
object, as shown in Figure 3. However, this method has poor scalability and
maintainability.

Figure3 Responsibility for creating a class object is encapsulated in a separate method


Introduction
• After long-term practice, software engineers have found a more scalable
method. This method is to separate the above method of creating an object
from the ClientGUI class, and create the object by another class. The design
encapsulates the choice of the class and the creation of the object in a
method (ie, a factory method) and encapsulates the method in a separate
class (ie, a factory class). As shown in Figure 4, the PolicyProducer class is a
factory class, where getInsurObj is a factory method.

Figure4 Responsibility for creating a class object is encapsulated in a separate class


Introduction

• The advantages of the factory method:


• Using factory methods to access and initialize objects of the
appropriate class simplifies the application. The application itself no
longer contains a large number of conditional statements to
determine which class to select.
• The factory method implements some special initial class
mechanism, especially when the different hierarchical classes require
different initialization methods.
• The factory method returns an object of the parent class, and the
client program does not need to know the existence of this initialized
class.
• Factory method design patterns can be divided into simple factory
method patterns, factory method patterns, and abstract factory
patterns.
Simple Factory

Figure5 Simple factory class diagram

• The design class diagram for the simple factory method pattern is
shown in Figure 5. The Creator class in the figure is a factory class.
The class in the right half of the figure is called the product class
and consists of the interface Product and concrete product class
ConcreteProduct.
Simple Factory

Figure5 Simple factory class diagram

Creator cr = new Creator();


Product p = [Link](“option”); [Link]();
Simple Factory
• Advantage
− The factory class includes business logic that selects the initial class from
the structure of a class and achieves separation of responsibilities.
− The client class does not have responsibility for creating objects of the
class. There are no conditional statements required to create the object.
Therefore, if a new product subclass is added, the existing client class
code does not have to be modified.
• Disadvantages
− The factory class must know how to create an object for each subclass,
and whenever the product class is added, the factory class code needs to
be modified.
Factory

Figure6 Factory class


diagram

• In order to overcome the shortcomings of the simple factory method model, people try
to improve the structure of the factory class. Software designers have found that it is
possible to solve this problem by rewriting a single factory class in a simple factory
method schema to a hierarchical class. First you need an interface as a superclass called
creator. There is a method in the interface called factory(); then you can use the same
structure as the product class to create the creator class structure, which contains
creatorA and creatorB, each responsible for creating the corresponding ProductA And
ProductB objects, as shown in Figure 6. In Figure 6, each product class corresponds to a
factory class. The factory class is only responsible for creating the corresponding product
class object.
Factory

Figure6 Factory class


diagram

Creator cr = null;
if ( x = a ) cr = new CreatorA();
else
cr = new CreatorB();
Product p = [Link]();
Factory Example

Figure7 User interface of


car insurance
management program
designed using factory
method pattern

• Use the factory method model to design the car insurance management
application of Example 1. The application have a user graphical interface,
as shown in Figure 7. On the user graphical interface shown in Figure 7,
the user can select different types of insurance and then click on the
“Show Info” button. The description of this type of insurance will then
be displayed in the upper part of the graphical interface.
Factory Example

Figure8 Car insurance


management
application designed
using factory method
mode

• According to the factory method pattern, the following design


class diagram is obtained. The difference from the simple factory
method pattern is that in the simple factory method pattern, the
PolicyProducer is a separate class, and the PolicyProducer class of
the factory method pattern is not a separate class but a
hierarchical class. The design class diagram is shown in Figure 8.
Factory Example

Figure8 Car insurance


management
application designed
using factory method
mode

PolicyProducer pp = null;
if ( x = “BodyPolicy” ) pp = new BodyPolicy();
else if ( x = “Collision” ) pp = new CollPolicy();
else if ( x = “PersonInjure” ) pp = new PersonPolicy();
else if ( x = “Property” ) pp = new PropPolicy();
else if ( x = “Comprehensive” ) pp = new ComPolicy(); AutoInsurance ai =
[Link]();
Factory

• The difference between the simple factory mode and the


factory method pattern
− The two models have different centers.
− Whether to support the Open Closed Principle
− Create the position of the object logic judgment.
• Application scenario of factory method pattern
− The logic of creating objects of certain classes is more complex and
may also add new conditions
− Need to encapsulate the logic of creating class objects, making these
logical localizations
Abstract Factory—Introduction

Figure 9 Three products with the same form

• If there are more than two sets of product classes with the same structure,
can you also use the factory method model? For example, there are three
sets of products, Shoes, Suit, and Tie, as shown in Figure 9. Products are
divided into male and female categories. Question: Is it possible to use the
above factory method mode at this time? If the answer is yes, how to apply
the factory method mode?
• Solution 1: Create a Creator hierarchy class for each product hierarchy class.
One drawback of this approach is that it requires at least 3 Creator level
classes. This approach is feasible but too cumbersome.
Abstract Factory—Introduction

Figure 10 Responsibility
for creating three sets
of product objects with
one factory category

• Solution 2: The above three hierarchical classes have the same structure,
and the above-mentioned factory method pattern can be modified so that
only one plant level class can take responsibility for creating three sets of
product objects. The design is shown in Figure 2.10.
Abstract Factory—Introduction

Figure 10 Responsibility
for creating three sets
of product objects with
one factory category

Creator cr = null;
if ( x ==a ) cr = new ConcreteCreatorA();
else if ( x == b ) cr = new ConcreteCreatorB();
if ( y = “ManTie” ) ManTie mt = [Link]();
else if ( y = “WomanTie” ) WomanTie wt = [Link]();
else if ( y = “ManShoes” ) ManShoes ms = [Link]();
else if ( y = “WomanShoes” ) WomanShoes ws = [Link]();
else if ( y = “ManSuit” ) ManSuit msi = [Link]();
else if ( y = “WomanSuit” ) WomanSuit wsi = [Link]():
Abstract Factory—Introduction

Figure 11 Abstract factory pattern design class diagram - two product categories

The Abstract Factory Pattern contains two product class abstract


factory pattern design class diagram as shown in Figure 11.
Abstract Factory—Introduction

Figure 11 Abstract factory pattern design class diagram - two product categories
Creator cr = null;
if ( x == 1 ) cr = new ConcreteCreatorA();
else if ( x == 2 ) cr = new ConcreteCreatorB();
if ( y == A ) Product a = [Link]();
else Product b = [Link]();
Abstract Factory—Example
• Design a home sales inquiry system to query the introduction, prices and
addresses of different types of houses. For the sake of simplicity, only two
types of houses are considered: the House and the Condo. And suppose that
each type of house contains: Super and Medium.
• Since House and Condo are classified into two categories, Super and
Medium, and the villa structure and the apartment structure have the same
structure, you can consider using the abstract factory pattern to design the
house search system.

Figure 12 Figure 13
Abstract Factory—Example

Figure 14

BuildingFactory bf = [Link](“option”);
if ( x == “House” ) House hs = [Link]();
else if ( x == “Cando” ) Cando cd = [Link]();
Abstract Factory—Example
• The scalability of Abstract factory pattern

Figure 15 Abstract Factory Pattern Design Class Diagram - Two Product Classes
Abstract Factory—Example

Figure 16 Abstract Factory


Pattern Design Class
Diagram –conform to
Open and Close Principles

• If you need to increase ProductA3 and ProductB3, the factory


class class needs to increase the class ConcreteCreator3. In this
case, the abstract factory pattern conform to the opening and
closing principle.
Abstract Factory—Example

Figure 17 Abstract Factory


Pattern Design Class
Diagram –does not
conform to Open and
Close Principles

• If you want to add a new product hierarchy class, ProductC, you


must add a method to each factory real class. +getObjC In this
case, the abstract factory pattern does not conform to the
opening and closing principle.

You might also like