Java 原型模式

2021-02-18  本文已影响0人  索性流年

文集地址

概述

原型模式与工厂模式有什么区别

优缺点

简单应用

/**
 * 原型抽象对象
 * @author ext.liuyan10
 * @date 2021/2/7 14:06
 */
public abstract class Prototype implements Cloneable{
    protected String name;

    public String getName() {
        return name;
    }

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

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

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

/**
 * 抽象对象实现
 * @author ext.liuyan10
 * @date 2021/2/7 14:06
 */
public class ConcretePrototype extends Prototype {
    public ConcretePrototype(String name) {
        super(name);
    }
    public void printingName(){
        System.out.println(this.name);
    }
}

/**
 * @author ext.liuyan10
 * @date 2021/2/7 11:31
 */
public class PrototypeApp {
    public static void main(String[] args) {
        ConcretePrototype prototype = new ConcretePrototype("初始对象");
        prototype.printingName();
        for (int i = 0; i < 2; i++) {
            try {
                if (prototype.clone() instanceof ConcretePrototype) {
                    ConcretePrototype clone = (ConcretePrototype) prototype.clone();
                    clone.setName("克隆对象"+i);
                    prototype.printingName();
                    clone.printingName();
                }
            } catch (CloneNotSupportedException e) {
                System.err.println(e.toString());
            }
        }
    }
}
初始对象
初始对象
克隆对象0
初始对象
克隆对象1
Disconnected from the target VM, address: '127.0.0.1:50185', transport: 'socket'

Process finished with exit code 0

上一篇下一篇

猜你喜欢

热点阅读