0% found this document useful (0 votes)
2 views10 pages

Comprehensive Guide to Design Patterns

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

Comprehensive Guide to Design Patterns

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

Design Patterns

I. Creational Design Patterns:


1. Singleton
- Eager initialization:
public class EagerInitializedSingleton {

private static final EagerInitializedSingleton INSTANCE = new


EagerInitializedSingleton();

// Private constructor to avoid client applications to use constructor


private EagerInitializedSingleton() {

public static EagerInitializedSingleton getInstance() {


return INSTANCE;
}
}
- Static block initialization:

public class StaticBlockSingleton {

private static final StaticBlockSingleton INSTANCE;

private StaticBlockSingleton() {
}

// Static block initialization for exception handling


static {
try {
INSTANCE = new StaticBlockSingleton();
} catch (Exception e) {
throw new RuntimeException("Exception occured in creating
singleton instance");
}
}

public static StaticBlockSingleton getInstance() {


return INSTANCE;
}
}

-Lazy Initialization:
public class LazyInitializedSingleton {

private static LazyInitializedSingleton instance;

private LazyInitializedSingleton() {
}

public static LazyInitializedSingleton getInstance() {


if (instance == null) {
instance = new LazyInitializedSingleton();
}
return instance;
}
}

- Thread Safe Singleton:


public class ThreadSafeLazyInitializedSingleton {

private static volatile ThreadSafeLazyInitializedSingleton instance;

private ThreadSafeLazyInitializedSingleton() {
}

public static synchronized ThreadSafeLazyInitializedSingleton


getInstance() {
if (instance == null) {
instance = new ThreadSafeLazyInitializedSingleton();
}
return instance;
}
}

- Double Check Locking Singleton:

public class DoubleCheckLockingSingleton {

private static volatile DoubleCheckLockingSingleton instance;

private DoubleCheckLockingSingleton() {
}

public static DoubleCheckLockingSingleton getInstance() {


// Do something before get instance ...
if (instance == null) {
// Do the task too long before create instance ...
// Block so other threads cannot come into while initialize
synchronized ([Link]) {
// Re-check again. Maybe another thread has initialized before
if (instance == null) {
instance = new DoubleCheckLockingSingleton();
}
}
}
// Do something after get instance ...
return instance;
}
}

- Bill Pugh Singleton Implementation:

public class BillPughSingleton {

private BillPughSingleton() {
}

public static BillPughSingleton getInstance() {


return [Link];
}

private static class SingletonHelper {


private static final BillPughSingleton INSTANCE = new
BillPughSingleton();
}
}

- Phá vỡ cấu trúc Singleton Pattern bằng Reflection:


public class ReflectionBreakSingleton {

public static void main(String[] args)


throws InstantiationException, IllegalAccessException,
InvocationTargetException {

EagerInitializedSingleton instanceOne =
[Link]();
EagerInitializedSingleton instanceTwo = null;

Constructor<?>[] constructors =
[Link]();
for (Constructor<?> constructor : constructors) {
[Link](true);
instanceTwo = (EagerInitializedSingleton)
[Link]();
}

[Link]([Link]());
[Link]([Link]());
}
}

- Enum Singleton:
public enum EnumSingleton {

INSTANCE;
}

- Serialization and Singleton:


public class SerializedSingleton implements Serializable {

private static final long serialVersionUID = 1741825395699241705L;

private SerializedSingleton() {
}

private static class SingletonHelper {


private static final SerializedSingleton instance = new
SerializedSingleton();
}

public static SerializedSingleton getInstance() {


return [Link];
}

/**
* Special hook provided by serialization where developer can control
what object needs to sent.
* However this method is invoked on the new object instance created
by de serialization process.
*
* @return
* @throws ObjectStreamException
*/
// private Object readResolve() throws ObjectStreamException {
// return [Link];
// }
}
public class SingletonSerializedTest {

public static void main(String[] args) throws FileNotFoundException,


IOException, ClassNotFoundException {

SerializedSingleton serializedSingleton1 =
[Link]();
EnumSingleton enumSingleton1 = [Link];

ObjectOutput out = new ObjectOutputStream(new


FileOutputStream("[Link]"));
[Link](serializedSingleton1);
[Link](enumSingleton1);
[Link]();

// De-serialize from file to object


ObjectInput in = new ObjectInputStream(new
FileInputStream("[Link]"));
SerializedSingleton serializedSingleton2 = (SerializedSingleton)
[Link]();
EnumSingleton enumSingleton2 = (EnumSingleton) [Link]();
[Link]();

[Link]("serializedSingleton1 hashCode=" +
[Link]());
[Link]("serializedSingleton2 hashCode=" +
[Link]());
[Link]("enumSingleton1 hashCode=" +
[Link]());
[Link]("enumSingleton2 hashCode=" +
[Link]());
}
}

2. Factory
Một Factory Pattern bao gồm các thành phần cơ bản sau:

Super Class: môt supper class trong Factory Pattern có thể là một
interface, abstract class hay một class thông thường.
Sub Classes: các sub class sẽ implement các phương thức của supper
class theo nghiệp vụ riêng của nó.
Factory Class: một class chịu tránh nhiệm khởi tạo các đối tượng sub
class dựa theo tham số đầu vào. Lưu ý: lớp này là Singleton hoặc cung
cấp một public static method cho việc truy xuất và khởi tạo đối tượng.
Factory class sử dụng if-else hoặc switch-case để xác định class con đầu
ra.

3. Abstract Factory

4. Prototype
- Tạo bản sao mà vẫn đảm bảo hiệu quả
- Example:
abstract class Shape implements Cloneable
class Rectangle extends Shape
class Square extends Shapes
class Circle extends Shape
class ShapeCache contain: static Hashtable<String, Shape> shapeMap
//use
[Link]();
Shape clonedShape = (Shape) [Link]("1");
- Tạo bản sao mà vẫn đảm bảo hiệu quả
- Example:
abstract class Shape implements Cloneable
class Rectangle extends Shape
class Square extends Shapes
class Circle extends Shape
class ShapeCache contain: static Hashtable<String, Shape> shapeMap
//use
[Link]();
Shape clonedShape = (Shape) [Link]("1");

5. Builder

6. Dependency Injection
- 1 kiểu tiêm phụ thuộc bằng Constructor
- 1 kiểu tiêm phụ thuộc bằng Setter

7. MVC
User ---> Controller <---> Model <---> DB
^ |
| |
View <--------|

- Example:
class Student
class StudentView
class StudentController contains: Student,StudentView

II. Structural Design Patterns:


1. Adapter
- Cầu nối 2 interfaces ko tương thích
- Example:
interface MediaPlayer
interface AdvancedMediaPlayer
class VlcPlayer implements AdvancedMediaPlayer
class Mp4Player implements AdvancedMediaPlaye
class MediaAdapter implements MediaPlayer and contain
AdvancedMediaPlayer
class AudioPlayer implements MediaPlayer and contain MediaAdapter
- Giải thích:
MediaPlayer chỉ play đc mp3
AdvancedMediaPlayer play đc vlc và mp4
Ta muốn năng cấp MediaPlayer để play được cả mp3, vlc và mp4
Ta dùng 1 adapter implement MediaPlayer và chứa
AdvancedMediaPlayer
-> vậy là adapter đó chứa 2 đắc trưng của 2 interface
AudioPlayer là 1 MediaPlayer, nó muốn play thêm vlc và mp4 thì chỉ cần
gắn adapter dô

2. Facade
- Giúp che đi sự phức tạp của system, cúng cấp iterface để kết nối để
client
- Example:
interface Shape
class Rectangle implements Shape
class Square implements Shape
class Circle implements Shape
class ShapeMaker contains: Rectangle,Square,Circle
- Giải thích:
Chúng ta có nhiều lại hình khác nhau, phức tạp.
Ta dùng 1 nơi chứa tất cả chúng để người dùng chỉ cần tương tác thông
qua 1 nơi duy nhất là ShapeMaker

3. Composite
- Component(interface)
- Leaf implements Component
- Composite implements Component and contain List<Component>
- Example:

import [Link];
import [Link];

// Component
interface Task

// Leaf
class SimpleTask implements Task

// Composite
class TaskList implements Task contain List<Task> tasks;

// Client
Task simpleTask1 = new SimpleTask("Complete Coding");
Task simpleTask2 = new SimpleTask("Write Documentation");

// Creating a task list


TaskList projectTasks = new TaskList("Project Tasks");
[Link](simpleTask1);
[Link](simpleTask2);

// Nested task list


TaskList phase1Tasks = new TaskList("Phase 1 Tasks");
[Link](new SimpleTask("Design"));
[Link](new SimpleTask("Implementation"));
[Link](phase1Tasks);

// Displaying tasks
[Link]();

4. Decorator
[Link]
- Component: là một interface quy định các method chung cần phải có
cho tất cả các thành phần tham gia vào mẫu này.
- ConcreteComponent : là lớp hiện thực (implements) các phương thức
của Component.
- Decorator : là một abstract class dùng để duy trì một tham chiếu của đối
tượng Component và đồng thời cài đặt các phương thức của Component
interface.
- ConcreteDecorator : là lớp hiện thực (implements) các phương thức của
Decorator, nó cài đặt thêm các tính năng mới cho Component.
- Client : đối tượng sử dụng Component.

5. Bridge
Tách riêng cái thực thi và cái ảo. Khác thiết kế của OOP. Ý nghĩa
khác Adapter.
6. Flyweight
- Khi c
7. Ssss
8. ss
[Link]

You might also like