设计模式(7)-原型模式
2019-06-21 本文已影响0人
zhglance
原型模式(Prototype Pattern)是用来创建重复的对象,降低创建对象的代价。
一、需求举例:
项目中需求开发应用场景:
1.简单的项目开发由初级工程师完成;
2.高难度的项目开发由高级工程师完成。
二、类图
三、代码实例
1.工程师抽象类:Engineer
package com.lance.prototype;
public abstract class Engineer implements Cloneable {
private String duty;
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty;
}
private String engineerName;
public String getEngineerName() {
return engineerName;
}
public void setEngineerName(String engineerName) {
this.engineerName = engineerName;
}
abstract void develop(String program);
@Override
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
- 工程师实现类:EngineerImpl
package com.lance.prototype;
public class EngineerImpl extends Engineer {
@Override
public void develop(String program) {
System.out.println(this.getDuty() +":"+ this.getEngineerName() + " develop " + program);
}
}
3.主类:PrototypePattern
package com.lance.prototype;
public class PrototypePattern {
public static void main(String[] args) {
System.out.println("==========start==========");
Engineer juniorEngineer = new EngineerImpl();
juniorEngineer.setDuty("工程师");
juniorEngineer.setEngineerName("张三(初级)");
juniorEngineer.develop("easy program");
System.out.println("=======================");
Engineer seniorEngineer = (EngineerImpl)juniorEngineer.clone();
seniorEngineer.setEngineerName("李四(高级)");
seniorEngineer.develop("difficult program");
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
工程师:张三(初级) develop easy program
=======================
工程师:李四(高级) develop difficult program
==========end==========