原型模式
原型模式主要是在我们设计代码是需要重复循环的new对象的时候使用,这样做的目的是提高效率复制一个对象会比你重新new对象会更快,clone是obj类中的一个方法,其作用域protected。实现原型模式只需要实现Cloneable接口,运行时存在的异常:CloneNotSupportedException(仅在未实现Cloneable接口时会抛出),原型模式一般与工厂模式共同出现使用。
public class CloneableTest implements Cloneable{
private Integer size;
private String name;
private BigDecimal money;
private Boolean state;
private ArrayList list = new ArrayList();
@Override
public CloneableTest clone(){
CloneableTest cloneableTest = null;
try {
cloneableTest = (CloneableTest) super.clone();
cloneableTest.list = (ArrayList)this.list.clone();
}catch (CloneNotSupportedException e){
e.printStackTrace();
}
return cloneableTest;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
public ArrayList getList() {
return list;
}
public void setList(ArrayList list) {
this.list = list;
}
}
public class ConcretePrototype extends CloneableTest{
public void show(){
System.out.println("原型模式实现类");
}
}
public class Test {
public static void main(String[] args) {
ConcretePrototype concretePrototype = new ConcretePrototype();
for (int i = 0; i < 10; i++) {
ConcretePrototype c = (ConcretePrototype) concretePrototype.clone();
c.setName("1111");
System.out.println(c.toString());
c.show();
}
}
}