Quick start with common design patterns - singleton mode, prototype mode

Singleton mode Singleton

The Singleton pattern (Singleton) allows you to ensure that a class has only one instance, and provides a global node to access the instance.

Applicable scene

  1. If a class in the program can only have one instance available to all clients.
  2. If you need tighter control over global variables.

core steps

  1. Making the default constructor private prevents other objects from using newthe operator of the singleton class.
  2. Create a new static build method as the constructor. This function will "secretly" call the private constructor to create the object and save it in a static member variable. All subsequent calls to this function will return this cache object.

different situations

single-threaded singleton

public final class Singleton {
    
    
    private static Singleton instance;
    public String value;
	
    // 隐藏构造函数
    private Singleton(String value) {
    
    
        this.value = value;
    }
	
    // 静态构造方法
    public static Singleton getInstance(String value) {
    
    
        if (instance == null) {
    
    
            instance = new Singleton(value);
        }
        return instance;
    }
}

// 实现
public class DemoSingleThread {
    
    
    public static void main(String[] args) {
    
    
        Singleton singleton = Singleton.getInstance("1");
        Singleton anotherSingleton = Singleton.getInstance("2");
        System.out.println(singleton.value); // 结果为1
        System.out.println(anotherSingleton.value); // 结果还是1
    }
}

multithreaded singleton

public final class Singleton {
    
    
    // 将instance用volatile关键字修饰,使得实例在多线程中可见
    private static volatile Singleton instance;

    public String value;

    private Singleton(String value) {
    
    
        this.value = value;
    }

    public static Singleton getInstance(String value) {
    
    
        // 使用双重检查锁定(DCL)方法,必须配合上面的volatile关键词修饰的instance才是完美的
        if (instance != null) {
    
     // 第一次检查,不通过就不需要执行下面的加锁和初始化操作,减少性能开销
            return result;
        }
        synchronized(Singleton.class) {
    
     // 锁
            if (instance == null) {
    
     // 第二次检查,能确定是否真正没有实例
                instance = new Singleton(value); // 创建单例
            }
            return instance;
        }
    }
}

// 实现
public class DemoMultiThread {
    
    
    public static void main(String[] args) {
    
    
        Thread threadFoo = new Thread(new ThreadFoo());
        Thread threadBar = new Thread(new ThreadBar());
        threadFoo.start();
        threadBar.start();
    }

    static class ThreadFoo implements Runnable {
    
    
        @Override
        public void run() {
    
    
            Singleton singleton = Singleton.getInstance("FOO");
            System.out.println(singleton.value);
        }
    }

    static class ThreadBar implements Runnable {
    
    
        @Override
        public void run() {
    
    
            Singleton singleton = Singleton.getInstance("BAR");
            System.out.println(singleton.value);
        }
    }
} // 最终都输出1

Prototype mode Prototype

The prototype pattern (Prototype) allows you to copy existing objects without making the code depend on the class they belong to.

Applicable scene

In code development, it is hoped that an exact replica of an object can be quickly generated without knowing all configurations and dependencies of the object.

scene simulation

Suppose we have a cell cellthat needs to undergo mitosis Mitosis, where the chromosomal content is complex and invisible.

Implementation process

  1. Create a prototype interface and declare 克隆methods in it.

    public interface Mitosis {
          
          
        // 接口声明放回类型的基类
        public Object doingMitosis();
    }
    
  2. The prototype class must additionally define a constructor that takes the object of this class as a parameter . The constructor must copy all member variable values ​​​​in the parameter object to the newly created entity. Every class must explicitly override the clone method and call the operator with its own class namenew . Otherwise, the clone method may produce an object of the parent class.

    public class Cell implements Mitosis {
          
          
        private String DNA;
    
        public Cell() {
          
          
            DNA = "AGCTGATCAAGTCTCGATC";
        }
    	// 一定要定义一个以该类对象为参数的构造函数,这是复制的入口
        public Cell(Cell cell) {
          
          
            if (cell != null) {
          
          
                // 复制参数对象中的所有成员变量值到新建实体中
                this.DNA = cell.DNA;
            }
        }
    
        public void geneEditing(String eDNA) {
          
          
            this.DNA = eDNA;
        }
    
        // 使用new运算符调用原型版本的构造函数
        @Override
        public Cell doingMitosis() {
          
          
            // 调用自身类名
            return new Cell(this);
        }
    
        @Override
        public boolean equals(Object object) {
          
          
            if (!(object instanceof Cell)) return false;
            Cell cell = (Cell) object;
            return cell.DNA == DNA;
        }
    }
    
  3. test

    public class Demo {
          
          
        public static void main(String[] args) {
          
          
            Cell cell = new Cell();
            cell.geneEditing("TAACGCTAGCTAGCTAGCT");
            // 有丝分裂
            Cell copyCell = cell.doingMitosis();
            // 比较遗传物质
            System.out.println(cell.equals(copyCell)); // true
        }
    }
    

Guess you like

Origin blog.csdn.net/qq_42078712/article/details/130295526