原型模式定义:
用原型对象指定创建对象的种类,并且通过复制这个对象创建新的对象。【深浅复制】,避免new浪费大量资源。
适用场合:
(1)产生对象比较复杂,初始化需要很多资源的时候;
(2)希望框架原型和产生对象分开的时候;
(3)同一个对象可能会供其他调用者同时调用的时候。
public class DayLife implements Cloneable{
private String getUp;
private String byBus;
private String buyFood;
private String noon;
private String afternoonWork;
private String goHome;
private String night;
public DayLife() {
/**
* 在使用clone的时候构造方法不执行,所以构造方法中的初始化就需要在clone的时候也做
*/
System.out.println("构造方法执行了");
}
public String getGetUp() {
return getUp;
}
public void setGetUp(String getUp) {
this.getUp = getUp;
}
public String getByBus() {
return byBus;
}
public void setByBus(String byBus) {
this.byBus = byBus;
}
public String getBuyFood() {
return buyFood;
}
public void setBuyFood(String buyFood) {
this.buyFood = buyFood;
}
public String getNoon() {
return noon;
}
public void setNoon(String noon) {
this.noon = noon;
}
public String getAfternoonWork() {
return afternoonWork;
}
public void setAfternoonWork(String afternoonWork) {
this.afternoonWork = afternoonWork;
}
public String getGoHome() {
return goHome;
}
public void setGoHome(String goHome) {
this.goHome = goHome;
}
public String getNight() {
return night;
}
public void setNight(String night) {
this.night = night;
}
public void printMessage(){
System.out.println(this.getGetUp());
System.out.println(this.getByBus());
System.out.println(this.getBuyFood());
System.out.println(this.getNoon());
System.out.println(this.getAfternoonWork());
System.out.println(this.getGoHome());
System.out.println(this.getNight());
}
@Override
public DayLife clone(){
try{
return (DayLife)super.clone();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public interface ILifeFactory {
public DayLife getInstance();
}
public class LifeFactoryImpl implements ILifeFactory {
private static DayLife dl = null;
@Override
public DayLife getInstance() {
if(dl==null){
System.out.println("new DayLife");
dl = new DayLife();
dl.setGetUp("早上七点起床");
dl.setByBus("乘坐公共汽车");
dl.setBuyFood("买一个5块钱的煎饼果子");
dl.setNoon("中午小憩一会儿");
dl.setAfternoonWork("下午拼命干活");
dl.setGoHome("欢天喜地地回家了");
dl.setNight("晚上自慰一会儿");
}else{
System.out.println("clone DayLife");
dl = dl.clone();
}
return dl;
}
}
测试
public class Client {
public static void main(String[] args) {
ILifeFactory lf = new LifeFactoryImpl();
lf.getInstance().printMessage();
System.out.println("-----------------------------");
DayLife dl = lf.getInstance();
dl.setGetUp("早上起床晚了,7:30才");
dl.printMessage();
System.out.println("-----------------------------");
DayLife dl2 = lf.getInstance();
dl2.setNight("自慰多了,身体虚了");
dl2.printMessage();
}
}