[go: up one dir, main page]

0% found this document useful (0 votes)
24 views6 pages

12 Design Patterns

The document discusses design patterns, which are standard solutions to common programming problems, and categorizes them into creational, structural, and behavioral patterns. It highlights the Singleton pattern as a popular example, detailing its implementation, advantages, and disadvantages. Additionally, it outlines the main elements of a design pattern and provides a framework for describing them.
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)
24 views6 pages

12 Design Patterns

The document discusses design patterns, which are standard solutions to common programming problems, and categorizes them into creational, structural, and behavioral patterns. It highlights the Singleton pattern as a popular example, detailing its implementation, advantages, and disadvantages. Additionally, it outlines the main elements of a design pattern and provides a framework for describing them.
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
You are on page 1/ 6

30/9/2021

1 2

Content
1. What are design patterns?
ITSS SOFTWARE DEVELOPMENT
2. How to describe a design pattern?
12. DESIGN PATTERNS 3. Design pattern categories

1 2

3 4

Design Patterns What and why design patterns?


• A standard solution to a common programming problem
• a design or implementation structure that achieves a particular
purpose
• Published in 1994
• a high-level programming idiom
• “Each pattern describes a problem which occurs over
• A technique for making code more flexible
and over again in our environment, and then describes
• reduce coupling among program components
the core of the solution to that problem, in such a way
that you can use this solution a million times over, • Short-hand for describing program design
without ever doing it the same way twice” • a description of connections among program components (static
structure)
• Christopher Alexander
• the shape of a heap snapshot or object model (dynamic behaviour)
• Today’s amazon.com stats

3 4

1
30/9/2021

5 6

Whence design patterns? An example of a GoF pattern


• Given a class A, what if you want to guarantee that there
• The Gang of Four (GoF) is precisely one instance of A in your program? And you
want that instance globally available?
• Gamma, Helm, Johnson, Vlissides
• First, why might you want this?
• Each an aggressive and thoughtful programmer • Second, how might you achieve this?

• Empiricists, not theoreticians


• Found they shared a number of “tricks” and
decided to codify them – a key rule was that
nothing could become a pattern unless they could
identify at least three real examples

5 6

7 8

Implementing Singleton Several solutions


• Make constructor(s) private so that they can not be public class Singleton {
private static final Singleton instance;
called from outside by clients. // Private constructor prevents instantiation from other classes
private Singleton() {
instance = new Singleton();
• Declare a single private static instance of the }
public static Singleton getInstance() { Eager allocation
class. return instance; of instance
}
}
• Write a public getInstance() or similar method that
public class Singleton {
allows access to the single instance. private static Singleton _instance;
private Singleton() { }
• May need to protect / synchronize this method to ensure that it will public static synchronized Singleton getInstance() {
work in a multi-threaded program. if (null == _instance) {
_instance = new Singleton();
} return _instance; Lazy allocation
} of instance
}

7 8

2
30/9/2021

9 10

Possible reasons for Singleton Singleton design patterns – diagram


• OneRandomNumber generator
• OneRestaurant, one ShoppingCart
• One KeyboardReader, etc…
• Make it easier to ensure some key invariants
• Make it easier to control when that single
instance is created – can be important for large
objects
•…

9 10

11 12

Content Main elements of a design pattern


• Pattern Name:
1. What are design patterns? • A common name to talk about

2. How to describe a design pattern? • Problem:


• Context: when to apply the pattern
3. Design pattern categories • May include a list of conditions for applying the pattern
• Solution:
• Abstract description of a design problem and how a general
arrangement of elements solves it
• Elements making up the design, their relationships/responsibilities
and collaborations
• Like a template, language-neutral
• Consequences:
• Results and tradeoff of applying patterns
• Impacts on system’s flexibility, extensibility or portability

11 12

3
30/9/2021

13 14

Describing a pattern Describing for Singleton pattern?


1. Name and 7. Collaboration
classification 8. Consequences
2. Also Known As 9. Implementations
3. Motivation 10. Sample Code
4. Applicability 11. Known Uses
5. Structure 12. Related Patterns
6. Participants

13 14

15 16

Singleton pattern Restricting objects


• Singleton: An object that is the only object of its type • One way to avoid creating objects: use static methods
(one of the most known / popular design patterns) • Examples: Math, System
• Ensuring that a class has at most one instance. • Is this a good alternative choice? Why or why not?
• Providing a global access point to that instance.
• e.g. Provide an accessory method that allows users to see the instance.

• Advantages: • Disadvantage: Lacks flexibility


• Takes responsibility of managing that instance away from the • Static methods can't be passed as an argument, nor returned.
programmer (illegal to construct more instances).
• Saves memory. • Disadvantage: Cannot be extended
• Avoids bugs arising from multiple instances. • Example: Static methods can't be sub-classed and overridden like
an object's methods could be.

15 16

4
30/9/2021

17 18

Singleton sequence diagram Singleton example


• Class RandomGenerator generates random numbers.

public class RandomGenerator {


private static final RandomGenerator gen =
new RandomGenerator();

public static RandomGenerator getInstance() {


return gen;
}

private RandomGenerator() {}

...
}

17 18

19 20

Lazy initialization Singleton Comparator


• Can wait until client asks for the instance to create • Comparators make great singletons because they have no state:

public class RandomGenerator { public class LengthComparator


private static RandomGenerator gen = null; implements Comparator<String> {
private static LengthComparator comp = null;
public static RandomGenerator getInstance() { public static LengthComparator getInstance() {
if (gen == null) { if (comp == null) {
gen = new RandomGenerator(); comp = new LengthComparator();
} }
return gen; return comp;
} }
private LengthComparator() {}
private RandomGenerator() {}
public int compare(String s1, String s2) {
... return s1.length() - s2.length();
} }
}

19 20

5
30/9/2021

21 22

Content GoF patterns: three categories


• Creational Patterns – these abstract the object-
1. What are design patterns? instantiation process
2. How to describe a design pattern? • Factory Method, Abstract Factory, Singleton,
Builder, Prototype
3. Design pattern categories • Structural Patterns – these abstract how objects/classes
can be combined
• Adapter, Bridge, Composite, Decorator,
Façade, Flyweight, Proxy
• Behavioral Patterns – these abstract communication
between objects
• Command, Interpreter, Iterator, Mediator,
Observer, State, Strategy, Chain of
Responsibility, Visitor, Template Method

21 22

23 24

Design Patterns classification Presentation of a Design Pattern (DP)


Purpose Creation Structure Behaviour • Name – Alias: Tên, tên gọi khác
Scope • Classification: Phân loại
Class Factory Adapter (class) Interpreter, • Intent: Mục đích
method Template Method
• Motivation: Khi nào cần sử dụng mẫu này
Object Abstract Adapter (object) Chain of Responsibility • Bài toán đặt ra
Factory
• Giải pháp nếu không dùng DP (nếu có)
Builder Bridge Command • Solution: Giải pháp khi dùng DP (ví dụ và tổng quát)
Prototype Composite Iterator • Biểu đồ lớp / Biểu đồ tương tác
Singleton Decorator Mediator • Mã nguồn minh hoạ
Façade Memento • Pros and cons
Flyweight Observer • Phân tích ưu nhược điểm khi sử dụng DP này

Proxy State, Strategy, Visitor • Applicability


• Các ví dụ ứng dụng trong thực tế, đặc biệt những ví dụ phổ biến

23 24

You might also like