Java设计模式之创建型模式(工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式)

五种创建型模式:

  • 工厂方法模式、
  • 抽象工厂模式、
  • 单例模式、
  • 建造者模式、
  • 原型模式。

1.工厂方法模式

简单理解:在工厂中创建需要的对象
假设现在生产AB两种类型汽车

public interface ICar {
    void run();
}
public class CarA implements ICar {
    @Override
    public void run() {
        System.out.println("CarA run...");
    }
}
public class CarB implements ICar {
    @Override
    public void run() {
        System.out.println("CarB run...");
    }
}

创建工厂生产汽车:

public interface Factory {
    ICar create();
}

public class AFactory implements Factory{
    @Override
    public ICar create() {
        return new CarA();
    }
}
public class BFactory implements Factory{
    @Override
    public ICar create() {
        return new CarB();
    }
}

测试一下:

public class FactoryTest {
    public static void main(String[] args) {
        Factory a = new AFactory();
        Factory b = new BFactory();
        a.create().run();
        b.create().run();
    }
}

2.抽象工厂模式

相比于工厂方法,抽象工厂一次可以创建更多对象,或一起创建产品的附属品
比如生产汽车的同时生产车载音响:

public class Audio(){
	public void run() {
        System.out.println("audio run...");
    }
}
public class AFactory implements Factory{
    @Override
    public ICar create() {
    	new Audio().run();
        return new CarA();
    }
}

3.单例模式

即只允许一个这样的实例存在
分为懒汉和恶汉,需要注意线程安全
以下是三种推荐的三种方式

/**
 * 饿汉式单例模式
 */
public class Singleton1 {
    private final static Singleton1 INSTANCE = new Singleton1();

    private Singleton1(){

    }

    public  static Singleton1 getInstance() {
        return INSTANCE;
    }
}
/**
 * 双重校验锁懒汉式
 */
public class Singleton2 {
    /**
     * volatile保证了不同线程对这个变量进行操作时的可见性,
     * 即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。
     */
    private static volatile Singleton2 singleton;

    private Singleton2(){

    }

    public static Singleton2 getInstance(){
        if(singleton == null){
            synchronized (singleton){
                if(singleton == null){
                    singleton = new Singleton2();
                }
            }
        }
        return singleton;
    }


}
/**
 * 静态内部类单例模式
 */
public class Singleton3 {
    private Singleton3(){

    }
    private static class SingletonInstance{
        private static final Singleton3 INSTANCE= new Singleton3();
    }
    public Singleton3 getInstance(){
        return SingletonInstance.INSTANCE;
    }

}

4.建造者模式

即通过一个建造者去组装你想要的东西
例如组装一台电脑:

public class Computer {
    String cpu;
    String memory;
    String graphicsCard;
    String mainborad;
    String hardDisk;
    String displayer;
    String keyboard;
    String mouse;

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getMemory() {
        return memory;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    public String getGraphicsCard() {
        return graphicsCard;
    }

    public void setGraphicsCard(String graphicsCard) {
        this.graphicsCard = graphicsCard;
    }

    public String getMainborad() {
        return mainborad;
    }

    public void setMainborad(String mainborad) {
        this.mainborad = mainborad;
    }

    public String getHardDisk() {
        return hardDisk;
    }

    public void setHardDisk(String hardDisk) {
        this.hardDisk = hardDisk;
    }

    public String getDisplayer() {
        return displayer;
    }

    public void setDisplayer(String displayer) {
        this.displayer = displayer;
    }

    public String getKeyboard() {
        return keyboard;
    }

    public void setKeyboard(String keyboard) {
        this.keyboard = keyboard;
    }

    public String getMouse() {
        return mouse;
    }

    public void setMouse(String mouse) {
        this.mouse = mouse;
    }
}

对应构造器:

public abstract  class ComputerBuilder {
    //setter注入
    Computer computer = new Computer();
    abstract  void buildCpu();
    abstract  void buildMemory();
    abstract  void buildGraphicsCard();
    abstract  void buildMainBoard();
    abstract  void buildHardDisk();
    abstract  void buildDisplayer();
    abstract  void buildKeyBoard();
    abstract  void buildMouse();

    Computer get(){
        return computer;
    }


}
public class BuilderA extends ComputerBuilder {


    @Override
    void buildCpu() {
        computer.setCpu("cpuA");
    }

    @Override
    void buildMemory() {
        computer.setMemory("memoryA");
    }

    @Override
    void buildGraphicsCard() {
        computer.setGraphicsCard("graphicsA");
    }

    @Override
    void buildMainBoard() {
        computer.setMainborad("mainboardA");
    }

    @Override
    void buildHardDisk() {
        computer.setHardDisk("hardDiskA");
    }

    @Override
    void buildDisplayer() {
        computer.setDisplayer("displayerA");
    }

    @Override
    void buildKeyBoard() {
        computer.setKeyboard("keyboardA");
    }

    @Override
    void buildMouse() {
        computer.setMouse("mouseA");
    }
}

店员采用构造器去构建:

public class Employee {
    ComputerBuilder computerBuilder;

    public Employee(ComputerBuilder computerBuilder) {
        this.computerBuilder = computerBuilder;
    }

    public Computer build(){
        computerBuilder.buildCpu();
        computerBuilder.buildDisplayer();
        computerBuilder.buildGraphicsCard();
        computerBuilder.buildHardDisk();
        computerBuilder.buildKeyBoard();
        computerBuilder.buildMainBoard();
        computerBuilder.buildMemory();
        computerBuilder.buildMouse();
        return computerBuilder.get();
    }
}

测试类:

public class ComputerShop {
    public static void main(String[] args) {
        ComputerBuilder computerBuilder = new BuilderA();
        Employee employee = new Employee(computerBuilder);
        Computer computer = employee.build();
        System.out.println(computer.toString());
    }
}

5.原型模式

深克隆,创建一个和自己一样的对象
(若采用引用方式,引用的对象改变后现有对象也会改变)
举例:孙悟空分身

/**
 * 孙悟空实现Cloneable接口克隆自己
 * @author datacharm.cn
 */
public class MonkeyKing implements Cloneable {
    private String name;

    public MonkeyKing(String name){
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

    /**
     * 克隆该实例
     */
    @Override
    public MonkeyKing clone(){
        MonkeyKing monkeyKing = null;
        try {
            monkeyKing = (MonkeyKing) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return monkeyKing;
    }
}

测试一下:

/**
 * 原型模式 - 对象深克隆
 * @author datacharm.cn
 */
public class ProtoTypeTest {
    public static void main(String[] args) {
        MonkeyKing m1 = new MonkeyKing("m1");
        System.out.println(m1+"-"+m1.getName());
        MonkeyKing m2 = m1.clone();
        System.out.println(m2+"-"+m2.getName());
    }
}

学习更多java内容 欢迎扫描左侧导航栏二维码关注我的公众号 编译未来

你可能感兴趣的:(Java)