建造者模式: 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
解决什么问题:
某些结构复杂的对象”的创建工作,由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口.
UML:
代码结构:
被拷贝的对象:
package com.prototype.pojo; /** * 被拷贝的对象 */ public class DayLife implements Cloneable { private String getUp; private String byBus; private String getFood; private String noon; private String afternoonWork; private String goHome; private String night; 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 getGetFood() { return getFood; } public void setGetFood(String getFood) { this.getFood = getFood; } 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 print() { System.out.println(this.getGetUp()); System.out.println(this.getByBus()); System.out.println(this.getGetFood()); 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; } }
被抽象的工厂:
package com.prototype.factory; import com.prototype.pojo.DayLife; /** * 被抽象的工厂 */ public interface ILifeFactory { DayLife getInstance(); }
工厂实现类:
package com.prototype.factory; import com.prototype.pojo.DayLife; /** * 工厂实现类 */ public class LifeFactoryImpl implements ILifeFactory { // 必须用静态变量来标明对象 private static DayLife dayLife = null; @Override public DayLife getInstance() { if (dayLife == null) { System.out.println("New Day Life"); dayLife = new DayLife(); dayLife.setGetUp("7:00起床"); dayLife.setByBus("7:30坐公交上班"); dayLife.setGetFood("8:30到公司,在公司附近吃早点"); dayLife.setNoon("吃中饭"); dayLife.setAfternoonWork("13:00开始下午工作"); dayLife.setGoHome("18:00下班"); dayLife.setNight("晚上娱乐"); } else { System.out.println("Clone Day Life"); dayLife = dayLife.clone(); } return dayLife; } }
拷贝实现:
package main; import com.prototype.factory.ILifeFactory; import com.prototype.factory.LifeFactoryImpl; import com.prototype.pojo.DayLife; /** * Created by Administrator on 2016/8/10. */ public class MainApp { public static void main(String[] args) { ILifeFactory factory = new LifeFactoryImpl(); factory.getInstance().print(); System.out.println("-----------------------"); DayLife dayLife = factory.getInstance(); dayLife.setGetUp("7:30起床"); dayLife.print(); System.out.println("-----------------------"); DayLife dayLife2 = factory.getInstance(); dayLife2.setGetUp("8:00起床"); dayLife2.print(); } }
时间: 2024-12-21 03:28:42