【设计模式】原型模式

原型模式:是用于创建重复的对象,当一个对象创建代价较大时,我们采用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

使用实例:工匠制造方桌的过程,我们都知道方桌有4条腿,为了保证桌子的稳定性,每条腿的长宽高都一样,但是后期再喷绘时,可能每条腿喷的颜色都不相同,那工匠在制造4条方桌的腿的时候,不能每次都去从新丈量它的长宽高,这就需要提前顶一个模版(原型产品),根据这个模版(原型产品),复制4条长宽高都一样凳子腿,然后再对每条腿喷绘,实例如下:

public class TableLeg implements Cloneable{
    private Integer _long;
    private Integer _width;
    private Integer _height;
    private String color;
    private static TableLeg tableLeg;
    private TableLeg(){

    }

    public Integer get_long() {
        return _long;
    }

    public void set_long(Integer _long) {
        this._long = _long;
    }

    public Integer get_width() {
        return _width;
    }

    public void set_width(Integer _width) {
        this._width = _width;
    }

    public Integer get_height() {
        return _height;
    }

    public void set_height(Integer _height) {
        this._height = _height;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    //模版制造一个新的TableLeg
    @Override
    public TableLeg clone() throws CloneNotSupportedException {
        return (TableLeg)super.clone();
    }
    @Override
    public String toString(){
        return "long="+_long+"\n"+"width="+_width+"\n"+"height="+_height+"\n"+"color="+color+"\n";
    }

    //单例模式创建原型模版
    public static TableLeg getIntance(){
        if (tableLeg==null){
            tableLeg = new TableLeg();
            tableLeg.set_height(50);
            tableLeg.set_long(10);
            tableLeg.set_width(10);
        }
        return tableLeg;
    }
    //获取复制的TableLeg
    public static TableLeg getTableLeg() throws CloneNotSupportedException {
        return getIntance().clone();
    }
}

原型模式的使用

public class PrototypeDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        TableLeg tableLeg1 = TableLeg.getTableLeg();
        tableLeg1.setColor("Red");
        System.out.println(tableLeg1);
        TableLeg tableLeg2 = TableLeg.getTableLeg();
        tableLeg2.setColor("Green");
        System.out.println(tableLeg2);
        TableLeg tableLeg3 = TableLeg.getTableLeg();
        tableLeg3.setColor("Black");
        System.out.println(tableLeg3);
        TableLeg tableLeg4 = TableLeg.getTableLeg();
        tableLeg4.setColor("Blue");
        System.out.println(tableLeg4);
    }
}

验证输出

long=10
width=10
height=50
color=Red

long=10
width=10
height=50
color=Green

long=10
width=10
height=50
color=Black

long=10
width=10
height=50
color=Blue



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值