Ten common design patterns, let you pass the interview at one time (gitbuh project: AlgorithmPractice)

Project Introduction

  • This project decomposes the common written interview questions of major factories, traces the source to the underlying implementation principles of data structures and algorithms, and knows what they are.
  • Establish a knowledge structure system for easy search, welcome more like-minded friends to join the project AlgorithmPractice, (issues and pull requests are welcome).

Ten common design patterns:

Start of text

1. Singleton singleton mode

  • Code implementation : Singleton
  • Design ideas :
    • In some scenarios, we need a class to provide only one instantiated object, so we make the constructor of the class private .
    • How do we get objects of this class after private? We provide a getInstance function externally to output private objects.
    • So where did this private object come from? If one defines the object at the beginning of the class, and then returns it through the getInstance function, we call it the hungry man mode (because it is too hungry, all the food/instance must be new to wait for me). If it is defined at the beginning, but when it is used later, new in the getInstance function and return, it becomes the lazy man mode.
    • Why is there a hungry man mode and a lazy man mode? The difference between the hungry man mode and the lazy man mode is when the new object is new. We know that the new object is a process that consumes resources and time. It needs CPU to schedule and allocate memory, especially for large objects, nested objects, which are often loaded. It's very slow, and if we load it when we actually use it, it will save time.
    • So, should I just use the lazy man mode? No, the lazy man mode is not used well, it will cause security problems, and multiple objects will appear, which violates the original intention of the singleton mode and further causes thread safety issues.
    • So how can it be used to ensure safety? It is guaranteed by locking synchronized, but locking will result in performance loss. What if this loss is reduced and the operation is safe? Introducing DCLSingletom, but is DCLSingletom necessarily safe? In fact, it is not. Because of the rearrangement of instructions, there is a certain chance that an error will occur when using the object (object attribute value is null).
    • Better suggestion? Use enumeration and internal fatigue to implement singleton mode.
  • Note :
    • When using synchronized, remember to cooperate with volatile to prohibit instruction rearrangement

2. Proxy mode

  • Code implementation : Proxy
  • Design ideas :
    • The emergence of the agency model is mainly based on the inheritance and rewrite characteristics of the development language
    • The proxy mode is to add some conventional operations before and after the real execution class. Some public methods that everyone will use. Common applications such as unified exception handling, unified log, unified error return, etc., all use the proxy mode to make the real The execution class is only related to the business itself, without excessive consideration of other situations.
    • Code display:
  • The proxy interface, the proxy class and the proxy class all need to implement it, and override its methods
public interface ProxyInterface {
    
    
    void work();
}
  • Proxy class
public class Proxy implements ProxyInterface {
    
    
    ProxyInterface p;
    public Proxy(ProxyInterface r) {
    
    
        // TODO Auto-generated constructor stub
        p = r;
    }
    @Override
    public void work() {
    
    
        // TODO Auto-generated method stub
        System.out.println("i am Proxy, i am help real's work,work begin");
        p.work();
        System.out.println("i am Proxy, work end");
    }
}
  • Real execution class
public class Real implements ProxyInterface {
    
    

    @Override
    public void work() {
    
    
        // TODO Auto-generated method stub
        System.out.println("i am real, i am doing work");
    }
}
  • Achieve effect
public class ProxyTest {
    
    

    @Test
    public void testProxy(){
    
    
        ProxyInterface r = new Real();
        ProxyInterface p = new Proxy(r);
        p.work();
    }
}
  • Note :
    • In design, the proxy class needs to consider more than the proxy class.

3. Strategy strategy mode

  • Code implementation : Strategy
  • Design ideas :
    • The strategy mode is actually similar to the agent mode in essence, and it is displayed after packaging one layer.
    • But the agent uses the rewrite of the class, and the strategy really uses the packaging, haha
    • The strategy uses a class as a container to package the actual class, and uses a uniform method to call the wrapped class.
    • The policy container and the policy interface have nothing to do with the proxy class and the proxy interface
    • Code
  • Policy interface
public interface Strategy {
    
    
    void method();
}
  • Strategy 1
public class strategy01 implements Strategy {
    
    
    @Override
    public void method() {
    
    
        // TODO Auto-generated method stub
        System.out.println("strategy01's method.");
    }
}
  • Strategy 2
public class strategy02 implements Strategy {
    
    
    @Override
    public void method() {
    
    
        // TODO Auto-generated method stub
        System.out.println("strategy02's method.");
    }
}
  • Strategy container
public class StrategyMethod {
    
    
    Strategy strategy;
    public StrategyMethod(Strategy strategy) {
    
    
        this.strategy = strategy;
    }
    public void opera() {
    
    
        strategy.method();
    }
}
  • actual effect
public class StrategyTest {
    
    
    @Test
    public void tetsStrategy(){
    
    
        Strategy s1 = new strategy01();
        Strategy s2 = new strategy02();
        StrategyMethod sm1 = new StrategyMethod(s1);
        sm1.opera();
        StrategyMethod sm2 = new StrategyMethod(s2);
        sm2.opera();
    }
}
  • Note :

4. Observer observer mode

  • Code implementation : Observer
  • Design ideas :
    • The observer mode is equivalent to the eyes in the game. The observer inserts an eye in the method of the observed. When the method of the observed is executed, the observer will receive the information and initiate the response method.
    • Therefore, a complete observer model includes: the observed and the observer.
    • The observer should have a method specifically to load the observer, and another method to notify the observer
    • Therefore, the observer should also have a callback method, which is waiting for the observer to trigger
    • Code
  • Observer
public class ObserverDemo {
    
    
    String name;
    public ObserverDemo(String name) {
    
    
        this.name = name;
    }
    public void lister() {
    
    
        System.out.println(name + " --> 观察到异常,并采取行动");
    }
}
  • Observed
public class ObservableDemo {
    
    
    List<ObserverDemo> list = new ArrayList<>();
    public void attach(ObserverDemo observerDemo) {
    
    
        list.add(observerDemo);
    }
    public void normalaction() {
    
    
        System.out.println("ObservableDemo normalaction:普通方法不会引起观察 ");
    }
    public void action() {
    
    
        System.out.println("ObservableDemo action:特殊方法会引起观察");
        notification();
    }
    public void notification() {
    
    
        for (ObserverDemo o : list) {
    
    
            o.lister();
        }
    }
}
  • Achieve effect
public class ObserverTest {
    
    
    @Test
    public void Testobserer(){
    
    

        //被观察者
        ObservableDemo observableDemo = new ObservableDemo();
        //观察者
        ObserverDemo observerDemo1 = new ObserverDemo("observerDemo1");
        ObserverDemo observerDemo2 = new ObserverDemo("observerDemo2");
        //被观察者将观察者加入自己的方法内
        observableDemo.attach(observerDemo1);
        observableDemo.attach(observerDemo2);
        //被观察者触发某个方法
        observableDemo.action();
        System.out.println("-----------------");
        observableDemo.normalaction();

    }
}
ObservableDemo action:特殊方法会引起观察
observerDemo1 --> 观察到异常,并采取行动
observerDemo2 --> 观察到异常,并采取行动
-----------------
ObservableDemo normalaction:普通方法不会引起观察 
  • Note :

5. Visitor visitor mode

  • Code implementation : Visitor
  • Design ideas :
  • Note :

6, Factory factory mode

  • Code implementation : Factory
  • Design ideas :
  • Note :

7. Delegate delegation mode

  • Code implementation :
  • Design ideas :
  • Note :

8. Prototype prototype mode

  • Code implementation :
  • Design ideas :
  • Note :

9, Template template mode

  • Code implementation : Template
  • Design ideas :
    • The essence of template design pattern is a fixed algorithm framework
    • The parent class has a fixed template, but the specific implementation steps of the open template allow subclasses to rewrite
    • Code
  • father
public abstract class TemplateDemo {
    
    
    public final void template() {
    
    
        method1();
        method2();
        method3();
    }
    public void method1() {
    
    
        System.out.println("father class first stop");
    }
    public void method2() {
    
    
        System.out.println("father class second stop");
    }
    public void method3() {
    
    
        System.out.println("father class third stop");
    }
}
  • Subclass
public class SubTemplate extends TemplateDemo {
    
    
    @Override
    public void method1() {
    
    
        System.out.println("sub class first step");
    }
}
  • achieve
public class TemplateTest {
    
    
    SubTemplate subTemplate = new SubTemplate();
    @Test
    public void testTemplate() {
    
    
        subTemplate.template();
    }
}
  • Note :
    • The general template design pattern will be implemented with chain programming

10. Adapter mode

  • Code implementation : Adapter
  • Design ideas :
  • Note :

Guess you like

Origin blog.csdn.net/ljfirst/article/details/105470727