前言
之前的文章种学习了创建型设计模式中的工厂模式和单例模式,今天研究创建型设计模式的最后两种,即建造型模式和原型模式。
一、建造型模式
在《设计模式》一书中的定义是,将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。现在的建造者模式主要是通过链式调用来生成不同的配置。比如,要建造房子,但是房子的属性是可选的。代码示例如下:
public class House {
private final String type;
private final int layers;
private final int cost;
private House(Builder builder){
this.type = builder.type;
this.layers = builder.layers;
this.cost = builder.cost;
}
public void show(){
System.out.println("build a " + this.type + ", layer is : " + this.layers + ", cost is :" + this.cost);
}
public static class Builder{
private final String type;
private int layers = 2;
private int cost = 10;
public Builder(String type){
this.type = type;
}
public Builder layers(int layers){
this.layers = layers;
return this;
}
public Builder cost(int cost){
this.cost = cost;
return this;
}
public House build(){
return new House(this);
}
}
public static void main(String[] args) {
House house = new Builder("别墅").layers(2).cost(1000000).build();
house.show();
House house2 = new Builder("楼房").layers(20).cost(1000000).build();
house2.show();
}
}
将House的构造方法设置为私有的,所以外部不能通过new来创建一个对象,只能通过builder构建,对于必须配置的属性,通过builder的构造函数传入,对于可选的参数则通过链式调用(即返回this对象,指向对象本身)属性设置方法进行传入。如果不配置将使用默认配置。
程序运行结果如下:
build a 别墅, layer is : 2, cost is :1000000
build a 楼房, layer is : 20, cost is :1000000
可以看出根据不同的输入参数完成了对象的构建,也解释了前面关于建造型模式的定义:同样的构建过程通过设置不同的参数可以实现不同对象的创建。
二、原型模式
原型模式简单理解就是通过对一个已经存在的对象进行拷贝完成对象的创建。在Java中有一个简单的实现原型模式的方法,就是需要进行拷贝的类实现cloneable接口,代码示例如下:
public class ProtoType implements Cloneable{
public String type = "1213";
public boolean ice = true;
@Override
protected ProtoType clone() throws CloneNotSupportedException {
return (ProtoType) super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
ProtoType type = new ProtoType();
ProtoType type1 = type.clone();
System.out.println(type == type1);
//1比较地址 但是输出true
System.out.println(type.type == type1.type);
//比较值
System.out.println(type.type.equals(type1.type));
System.out.println(type.ice == type1.ice);
}
}
但是Java中自带的clone方法是浅拷贝的,也就是说调用clone方法,只有基本类型的参数会被拷贝一份,非基本类型的参数并不会拷贝,而只是指向了同一个内存地址。上面的代码示例中,1位置中对于String类型直接使用==比较的是两个字符串的地址,如果是深拷贝,则该位置输出false,但是代码的执行结果在位置1输出true,证明了Java中的clone方法是浅拷贝。
总结
建造者模式和原型模式都比较简单,熟悉即可。
代码仓地址:https://gitee.com/yongrenyue
如有错误,恳请大家批评指证,日拱一卒,功不唐捐。