How to understand these 6 common design patterns?

I. Introduction

Recently, in the transformation of some historical codes, I found a very obvious feature, most of the codes are narratives, and the stories are explained straightforwardly according to the development process of the event.

The advantage of this method is that it is more in line with human thinking habits. A main line is described in the end. The code is not too difficult to read. As long as you follow the vine, you can feel the melon, but the disadvantage is also obvious. Once you need to insert some new stories in the story line Elements such as: adding a new character, a new timeline will require a lot of changes to the story line to match the integration of this new element, and even have a destructive effect on the original article.

In order to solve this problem, people have summed up many kinds of article structures, such as: total-point structure, side-by-side structure, total-point-overall structure, etc. With these structures, when adding new elements, you don’t even need to consider new elements. For the relevance to the original storyline, just pull a branch storyline and tell it independently, as long as it can converge to the main story before the end of the overall story (is it very similar to git?).

In the field of software development, there are many such very useful practice summaries, which we call design patterns. No one is unfamiliar with design patterns. Anyone who finds it is estimated to be able to tell N design patterns, but in addition to the concepts of these design patterns, many people do not know how to use these design patterns flexibly. So take this article to learn the idea of ​​design patterns with everyone.

Two understand design patterns

I try to use the most easy-to-understand examples and language to describe the design patterns I understand, hoping to help everyone.

In addition, there is no need to be proficient in all design patterns, as long as you can integrate common design patterns, you can make your code elegant. Just like Cheng Yaojin only knows how to make three strikes, but his proficiency is unmatched, and he can still travel the world.

1 Factory mode (Factory)

Simple Factory

When Xiao Ming chased her sister, she invited her to drink a lot of coffee. She loves to drink cappuccino. Every time she goes to a coffee shop, she only needs to tell the waiter "a cup of cappuccino", although the tastes of each family are different , But whether it is Star Papa or Costa, they can provide cappuccino. Papa Star and Costa here are factories that produce coffee.

(1) Simple factory model structure

The simple factory pattern includes the following roles:

  • Factory: Factory role-responsible for implementing the internal logic of creating all instances.

  • Product: Abstract product role-is the parent class of all objects created, responsible for describing the common interface shared by all instances.

  • ConcreteProduct: specific product role-is the creation target, all created objects act as instances of a specific class of this role.

Structure diagram:

Timing diagram:

(2) Advantages and disadvantages

  • Advantages: The customer class and the factory class are separated. Consumers need a certain product at any time, just request it from the factory. Consumers can accept new products without modification.

  • Disadvantage: When the product is modified, the factory class must also be modified accordingly.

Factory Method

I used to take my wife to Uniqlo (simple factory) to buy clothes. With so many styles, she would be annoyed when she went shopping more often. Later, I changed my strategy and took my wife to the shopping mall (abstract factory). There are shops of various brands in the mall. Without me, she can go shopping all day.

Different from simple factories, the core factory category (shopping malls) is no longer responsible for the creation of all products, but instead delegates the specific creation work to the subcategories (clothing stores), becoming an abstract factory role, only responsible for giving specific factory categories The interface (store) that must be implemented without touching the details of which product class should be instantiated.

(1) Factory method pattern structure

The factory method pattern includes the following roles:

  • Product: abstract product

  • ConcreteProduct: specific product

  • Factory: Abstract Factory

  • ConcreteFactory: concrete factory

Structure diagram:

Timing diagram:

Summary of factory mode

(1) Applicable scenarios

The exported products are standard products, anyone can do it.

(2) Examples

The common database connection factory, SqlSessionFactory, is a database connection. As for whether it is provided by oracle or mysql, I don't need to care, because it allows me to manipulate data through sql.

(3) Matters needing attention

At the beginning of the project, when the software structure and requirements are not stable, it is not recommended to use this mode, because its disadvantages are also obvious, increasing the complexity of the code, increasing the call level, and increasing the memory burden. So pay attention to prevent the abuse of the model.

(4) Simple implementation

package FactoryMethod;
public class FactoryPattern
{
public static void main(String[] args)
{
        Factory factory = new ConcreteFactoryA();
        Product product = factory.createProduct();
        product.use();
    }
}
//抽象产品:提供了产品的接口
interface Product
{
public void use();
}
//具体产品A:实现抽象产品中的抽象方法
class ConcreteProductA implements Product
{
public void use()
{
        System.out.println("具体产品A显示...");
    }
}
//具体产品B:实现抽象产品中的抽象方法
class ConcreteProductB implements Product
{
public void use()
{
        System.out.println("具体产品B显示...");
    }
}
//抽象工厂:提供了厂品的生成方法
interface Factory
{
public Product createProduct();
}
//具体工厂A:实现了厂品的生成方法
class ConcreteFactoryA implements AbstractFactory
{
public Product createProduct()
{
        System.out.println("具体工厂A生成-->具体产品A.");
return new ConcreteProductA();
    }
}
//具体工厂B:实现了厂品的生成方法
class ConcreteFactoryB implements AbstractFactory
{
public Product createProduct()
{
        System.out.println("具体工厂B生成-->具体产品B.");
return new ConcreteProductB();
    }
}

2 Singleton mode (Singleton)

Wei Xiaobao has 7 wives, but each one is only his husband. When all his wives are called husbands, they refer to him, and he is a single case.

Singleton mode structure

The singleton mode includes the following roles:

  • Singleton: Singleton

Structure diagram:

Timing diagram:

Pros and cons

  • Advantages: There is only one instance globally, which is convenient for unified control and reduces system resource overhead.

  • Disadvantages: No abstraction layer, difficult to expand.

Application scenarios

It is suitable for scenarios that require global unified control, such as a globally unique code generator.

Precautions

Only public getInstance methods are provided to the outside world, and no public constructors are provided.

Simple implementation

public class Singleton
{
private static volatile Singleton instance=null;    //保证 instance 在所有线程中同步
private Singleton(){}    //private 避免类在外部被实例化
public static synchronized Singleton getInstance()
{
//getInstance 方法前加同步
if(instance == null)
        {
            instance = new Singleton();
        }
return instance;
    }
}

3 Decorator

After graduating from university, I wanted to give my roommate a commemorative gift. I found a photo of everyone and wrote "Forever Brother!" on it. Then I took it to the gift shop and installed a photo frame and wrapped it in a gift box. The gift shop and I here are both decorators, neither has changed the photo itself, but both made the photo more suitable as a gift.

Decoration pattern structure

The decoration mode includes the following roles:

  • Component: abstract component

  • ConcreteComponent: concrete component

  • Decorator: abstract decoration class

  • ConcreteDecorator: concrete decoration class

Structure diagram:

Timing diagram:

Pros and cons

  • Advantages: more flexible than inheritance (inheritance is a static relationship with a high degree of coupling), it can dynamically add responsibilities to the object, and can extend N new functions for the object by using different decorator combinations without affecting the object itself.

  • Disadvantages: When there are too many decorators for an object, a lot of small decorative objects and decoration combination strategies will be generated, increasing the complexity of the system and increasing the cost of code reading and comprehension.

Applicable scene

  • It is suitable for scenes that need (through configuration, such as diamond) to dynamically increase or decrease object functions.

  • Suitable for scenes where an object requires N kinds of functional permutations and combinations (if inheritance is used, the number of subclasses will explode)

Precautions

  • The interface of a decorated class must remain the same as the interface of the decorated class. For the client, both the object before decoration and the object after decoration can be treated consistently.

  • Try to keep the concrete component class Component as a "light" class, that is, don't put too much logic and state in the concrete component class, you can use the decoration class.

Simple implementation

package decorator;
public class DecoratorPattern
{
public static void main(String[] args)
{
        Component component = new ConcreteComponent();
        component.operation();
        System.out.println("---------------------------------");
        Component decorator = new ConcreteDecorator(component);
        decorator.operation();
    }
}
//抽象构件角色
interface  Component
{
public void operation();
}
//具体构件角色
class ConcreteComponent implements Component
{
public ConcreteComponent()
{
        System.out.println("创建具体构件角色");       
    }   
public void operation()
{
        System.out.println("调用具体构件角色的方法operation()");           
    }
}
//抽象装饰角色
class Decorator implements Component
{
private Component component;   
public Decorator(Component component)
{
this.component=component;
    }   
public void operation()
{
        component.operation();
    }
}
//具体装饰角色
class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
    }   
public void operation()
{
super.operation();
        addBehavior();
    }
public void addBehavior()
{
        System.out.println("为具体构件角色增加额外的功能addBehavior()");           
    }
}

4 Strategy mode (Strategy)

Boys usually use this model when chasing girls. Common strategies include these: eat on a date; watch a movie; watch a concert; go shopping; go traveling... Although they do different things, they can replace each other. The only goal They are all capturing the hearts of girls.

Strategy mode structure

  • Context: Environment class

  • Strategy: Abstract strategy class

  • ConcreteStrategy: specific strategy class

Structure diagram:

Timing diagram:

Pros and cons

  • Advantages: The strategy mode provides perfect support for the "opening and closing principle", and users can choose algorithms or behaviors without modifying the original system. Kill complex and ugly if-else.

  • Disadvantages: When calling, you must know in advance which strategy mode classes are available in order to decide by yourself which strategy should be used in the current scene.

Trial scenario

A system needs to dynamically select one of several alternative algorithms. Users do not want to care about the details of the algorithm, and encapsulate the specific algorithm into a strategy class.

Precautions

Be sure to explain the purpose and applicable scenarios of the strategy in the comments of the strategy class.

Simple implementation

package strategy;
public class StrategyPattern
{
public static void main(String[] args)
{
        Context context = new Context();
        Strategy strategyA = new ConcreteStrategyA();
        context.setStrategy(strategyA);
        context.algorithm();
        System.out.println("-----------------");
        Strategy strategyB = new ConcreteStrategyB();
        context.setStrategy(strategyB);
        context.algorithm();
    }
}
//抽象策略类
interface Strategy
{   
public void algorithm();    //策略方法
}
//具体策略类A
class ConcreteStrategyA implements Strategy
{
public void algorithm()
{
        System.out.println("具体策略A的策略方法被访问!");
    }
}
//具体策略类B
class ConcreteStrategyB implements Strategy
{
public void algorithm()
{
      System.out.println("具体策略B的策略方法被访问!");
  }
}
//环境类
class Context
{
private Strategy strategy;
public Strategy getStrategy()
{
return strategy;
    }
public void setStrategy(Strategy strategy)
{
this.strategy=strategy;
    }
public void algorithm()
{
        strategy.algorithm();
    }
}

5 Proxy mode (Proxy)

Taobao shop customer service will always receive a lot of repeated questions, such as: Is there any stock? When will it be shipped? What kind of express delivery? Answering a large number of repetitive questions was too annoying, so Xiaomi robot appeared, he came to help customer service to answer those known questions, and when he encountered a question that Xiaomi could not answer, he would go to manual customer service. The Xiaomi robot here is the customer service agent.

Agency model structure

The proxy mode includes the following roles:

  • Subject: Abstract topic role

  • Proxy: Proxy theme role

  • RealSubject: Real Subject Role

Structure diagram:

Timing diagram:

Pros and cons

  • Advantages: The agent can coordinate the caller and the callee, which reduces the coupling of the system. According to different agent types and scenarios, it can play a role in controlling security and reducing system overhead.

  • Disadvantages: A layer of proxy processing is added, which increases the complexity of the system and may reduce the corresponding speed of the system.

Trial scenario

In theory, it can proxy any object. The common proxy modes are:

  • Remote proxy: Provide a local proxy object for an object located in a different address space. This different address space can be in the same host or in another host. The remote proxy is also called the ambassador ( Ambassador).

  • Virtual agent: If you need to create an object that consumes a lot of resources, first create an object that consumes a relatively small amount to represent it. The real object will only be created when needed.

  • Copy-on-Write agent: It is a type of virtual agent that delays the copy (clone) operation until it is executed only when the client really needs it. Generally speaking, the deep cloning of an object is a costly operation. The Copy-on-Write agent can delay this operation, and the object is cloned only when it is used.

  • Protection (Protect or Access) agent: Controls access to an object, and can provide different users with different levels of access.

  • Cache agent: Provide temporary storage space for the results of a certain target operation so that multiple clients can share these results.

  • Firewall (Firewall) proxy: protect the target from malicious users.

  • Synchronization (Synchronization) agent: enables several users to use an object at the same time without conflict.

  • Smart Reference Agent: When an object is referenced, it provides some additional operations, such as recording the number of times the object is called.

Simple implementation

package proxy;
public class ProxyPattern
{
public static void main(String[] args)
{
        Proxy proxy = new Proxy();
        proxy.request();
    }
}
//抽象主题
interface Subject
{
void request();
}
//真实主题
class RealSubject implements Subject
{
public void request()
{
        System.out.println("访问真实主题方法...");
    }
}
//代理
class Proxy implements Subject
{
private RealSubject realSubject;
public void request()
{
if (realSubject==null)
        {
            realSubject=new RealSubject();
        }
        preRequest();
        realSubject.request();
        afterRequest();
    }
public void preRequest()
{
        System.out.println("访问真实主题之前的预处理。");
    }
public void afterRequest()
{
        System.out.println("访问真实主题之后的后续处理。");
    }
}

6 Observer mode (Observer)

You are on a business trip and want to know the situation of your child at home. At this time, you just need to join the “family family” group. Moms and dads will often post photos and videos of their children to the group. All you have to do is to be an observer, You can understand everything just by swiping the information in the group.

Observer pattern structure

The observer mode includes the following roles:

  • Subject: target

  • ConcreteSubject: specific goal

  • Observer: Observer

  • ConcreteObserver: specific observer

Structure diagram:

Timing diagram:

Pros and cons

  • Advantages: Turn the complex serial processing logic into unitized independent processing logic. The observers just send out messages according to their own logic, and don't care who consumes the messages. Each observer only deals with what he cares about. Logic isolation brings a simple and refreshing code structure.

  • Disadvantages: When there are many observers, it may spend a certain amount of overhead to send a message, but the message may only be consumed by one observer.

Applicable scene

It is suitable for one-to-many business scenarios. When one object changes, it will trigger N objects to do the corresponding processing. For example: order scheduling notification, task status change, etc.

Precautions

Avoid forming a circular dependency between the observer and the observed, which may cause the system to crash.

Simple implementation

package observer;
import java.util.*;
public class ObserverPattern
{
public static void main(String[] args)
    {
        Subject subject = new ConcreteSubject();
        Observer obsA = new ConcreteObserverA();
        Observer obsb = new ConcreteObserverB();
        subject.add(obsA);
        subject.add(obsB);
        subject.setState(0);
    }
}
//抽象目标
abstract class Subject
{
protected List<Observer> observerList = new ArrayList<Observer>();   
//增加观察者方法
public void add(Observer observer)
    {
        observers.add(observer);
    }    
//删除观察者方法
public void remove(Observer observer)
    {
        observers.remove(observer);
    }   
public abstract void notify(); //通知观察者方法
}
//具体目标
class ConcreteSubject extends Subject
{
private Integer state;
public void setState(Integer state){
this.state = state;


// 状态改变通知观察者
        notify();
    }
public void notify()
    {
        System.out.println("具体目标状态发生改变...");
        System.out.println("--------------");       


for(Observer obs:observers)
        {
            obs.process();
        }


    }          
}
//抽象观察者
interface Observer
{
void process(); //具体的处理
}
//具体观察者A
class ConcreteObserverA implements Observer
{
public void process()
    {
        System.out.println("具体观察者A处理!");
    }
}
//具体观察者B
class ConcreteObserverB implements Observer
{
public void process()
    {
        System.out.println("具体观察者B处理!");
    }
}

There is no way, but the technique can be achieved; if there is no way, it ends with the technique

Welcome everyone to follow the Java Way public account

Good article, I am reading ❤️

Guess you like

Origin blog.csdn.net/hollis_chuang/article/details/108570821