Java design patterns

1. Factory

​ Through upward modeling and dynamic binding to achieve unified object management, high cohesion and development friendly

​ Generally speaking, the original need to instantiate the target class through the class name, now only need to instantiate a factory, by calling the factory method to complete the instantiation of the target class, and the instantiation of the target class is the entry (interface) of the program, using the characteristics of Java dynamic binding to complete the call of specific methods (interface implementation class).

1.1 Simple Factory

Draw

public interface Draw {
    void drawing();
}

DrawCircle

public class DrawCircle implements Draw{
    @Override
    public void drawing() {
        System.out.println("Drawing a circle");
    }
}

DrawSquare

public class DrawSquare implements Draw{
    @Override
    public void drawing() {
        System.out.println("Drawing a square");
    }
}

DrawFactory

public class DrawFactory {
    public Draw drawing(String shape) {
        switch (shape) {
            case "Circle":
                return new DrawCircle();
            case "Square":
                return new DrawSquare();
            default:
                return null;
        }
    }
}

1.2 Complex Factory

DrawFactoryComplex

![Theory](00_Pra/Theory.png)public class DrawFactoryComplex {
    public Draw drawCircle(){
        return new DrawCircle();
    }

    public Draw drawSquare(){
        return new DrawSquare();
    }
}

1.3 Static Factory

DrawFactoryStatic

public class DrawFactoryStatic {
    public static Draw drawCircle(){
        return new DrawCircle();
    }

    public static Draw drawSquare(){
        return new DrawSquare();
    }
}

1.4 Summarize

  • Theory

    • Upward molding and dynamic binding
    • User-friendliness
    • High cohesion

2. Singleton

​ The core principle of the singleton design pattern is to ensure the global uniqueness of the object, so the static keyword is used to embellish, initializing with the program starts and closing with the program closes

2.1 lazy

public class SingletonLazy {

    private static SingletonLazy instance;

    private SingletonLazy() {
    }

    public static SingletonLazy getInstance() {
        if (instance == null) {
            instance = new SingletonLazy();
        }
        return instance;
    }
}

2.2 lazy safety

public class SingletonLazySynchronized {
    private static SingletonLazySynchronized instance;

    private SingletonLazySynchronized() {
    }

    public static synchronized SingletonLazySynchronized getInstance() {
        if (instance == null) {
            instance = new SingletonLazySynchronized();
        }
        return instance;
    }

}

2.3 Stave

public class SingletonStarve {
    private static SingletonStarve instance = new SingletonStarve();

    private SingletonStarve(){}

    public static SingletonStarve getInstance(){
        return instance;
    }
}

2.4 Double checked locking

public class SingletonDoubleCheckedLocking {

    private volatile static SingletonDoubleCheckedLocking instance;

    private SingletonDoubleCheckedLocking() {
    }

    public static SingletonDoubleCheckedLocking getInstance() {
        if (instance == null) {
            synchronized (SingletonDoubleCheckedLocking.class) {
                if (instance == null) {
                    instance = new SingletonDoubleCheckedLocking();
                }
            }
        }
        return instance;
    }
}

2.5 Register

public class SingletonRegister {

    private static class SingletonHolder {
        private static final SingletonRegister INSTANCE = new SingletonRegister();
    }

    private SingletonRegister() {
    }

    public static final SingletonRegister getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

2.6 Enum

public enum SingletonEnum {

    INSTANCE;
    public void whateverMtthod(){}

}

2.7 Summarize

  • Globally unique

3. Abstract

​ The core principle of the abstract design pattern is the same as that of the factory design pattern, which is upward modeling and dynamic binding. The design pattern is implemented based on the abstract class and has all the characteristics of the abstract class.
Animal

abstract class Animal {
    abstract void move();
}

Bird

public class Bird extends Animal{
    @Override
    void move() {
        System.out.println("Fly");
    }
}

Fish

public class Fish extends Animal{
    @Override
    void move() {
        System.out.println("Swimming");
    }
}

AnimalFactory

public abstract class AnimalFactory {
    public abstract Animal createAnimal();
}

BirdFactory

public class BirdFactory extends AnimalFactory{
    @Override
    public Animal createAnimal() {
        return new Bird();
    }
}

FishFactory

public class FishFactory extends AnimalFactory{
    @Override
    public Animal createAnimal() {
        return new Fish();
    }
}

Summarize

  • Upward molding and dynamic binding
  • User-friendliness
  • High cohesion

4. Builder

can create a composite object,specific implementation is created one by one

/**
 * <P>ProjectName:  [095-OWNER]
 * <P>ClassName:   [Builder]
 * <P>Description: [Builder pattern]
 * <P>CreateDate:  [2024-09-10 10:43:17]
 * <P>UpdateDate:  [2024-09-10 10:43:17]
 *
 * @author [MTing]
 * @version [v1.0]
 * <P>Tip          [Attention:The source code is only circulated by relevant research and development personnel,
 * and it is prohibited to leak or use for other commercial purposes without permission.]
 * @see [Related classes and methods]
 * @since [Product template version]
 */
public class Builder {

    private List<Draw> draws = new ArrayList<Draw>();
    private List<Animal> animals = new ArrayList<Animal>();

    public void drawingCircle(int count) {
        for (int i = 0; i < count; i++) {
            draws.add(new DrawCircle());
        }
    }

    public void drawingSquare(int count) {
        for (int i = 0; i < count; i++) {
            draws.add(new DrawSquare());
        }
    }

    public void aninalBird(int count) {
        for (int i = 0; i < count; i++) {
            animals.add(new Bird());
        }
    }

    public void aninalFish(int count) {
        for (int i = 0; i < count; i++) {
            animals.add(new Fish());
        }
    }
     public SingletonLazy createSingletonLazy() {
        SingletonLazy instance = SingletonLazy.getInstance();
        return instance;
    }
}
/**
 * <P>ProjectName:  [095-OWNER]
 * <P>ClassName:   [BuilderTest]
 * <P>Description: [BuilderTest]
 * <P>CreateDate:  [2024-09-10 10:46:31]
 * <P>UpdateDate:  [2024-09-10 10:46:31]
 *
 * @author [MTing]
 * @version [v1.0]
 * <P>Tip          [Attention:The source code is only circulated by relevant research and development personnel,
 * and it is prohibited to leak or use for other commercial purposes without permission.]
 * @see [Related classes and methods]
 * @since [Product template version]
 */
public class BuilderTest {

    public static void main(String[] args) {
        Builder builder = new Builder();
        builder.drawingCircle(10);
        builder.drawingSquare(10);
        builder.aninalBird(10);
        builder.aninalFish(10);
        builder.createSingletonLazy();
    }
}

5. Prototype

Create objects by copying prototypes

Shallow cloning:A reference to a cloned object

Deep cloning:A instance to clone object

/**
 * <P>ProjectName:  [095-OWNER]
 * <P>ClassName:   [Prototype]
 * <P>Description: [Prototype]
 * <P>CreateDate:  [2024-09-11 09:44:08]
 * <P>UpdateDate:  [2024-09-11 09:44:08]
 * <P>Logic:[Create objects by copying prototypes  Shallow cloning:A reference to a cloned object  Deep cloning:A instance to clone object]
 *
 * @author [MTing]
 * @version [v1.0]
 * <P>Tip          [Attention:The source code is only circulated by relevant research and development personnel,
 * and it is prohibited to leak or use for other commercial purposes without permission.]
 * @see [Related classes and methods]
 * @since [Product template version]
 */
public class Prototype implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;

    private String name;
    private QuoteObject obj;

    public Object shallowClone() throws CloneNotSupportedException {
        return (Prototype) super.clone();
    }

    public Object deepClone() throws CloneNotSupportedException, IOException, ClassNotFoundException {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(this);
        objectOutputStream.close();


        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

        Object o = objectInputStream.readObject();
        objectInputStream.close();
        return o;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public QuoteObject getObj() {
        return obj;
    }

    public void setObj(QuoteObject obj) {
        this.obj = obj;
    }
}

class QuoteObject implements Serializable {
    private static final long serialVersionUID = 1L;
}

MTingCat
12 声望2 粉丝

一路向阳。


下一篇 »
SQL Server