本文最后更新于 2024-12-18T22:58:05+08:00
概念 原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
优点
与每次new对象相比,每NEW一次,都需要执行 一次构造函数,如果构造函数的执行时间很长,那么多次的执行这个初始化操作就实在是太低效了。 一般在初始化的信息不发生变化的情况下,克隆是 最好的办法。这既隐藏了对象创建的细节,又对性能是大大的提高。
不用重新初始化对象,而是动态地获得对象运行时的状态
示例 原型接口,包括copy方法用来实现原型对象的克隆
1 2 3 4 5 public abstract class Prototype <T> implements Cloneable { public T copy () { return (T) super .clone(); } }
Beast类、OrcBeast类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public abstract class Beast extends Prototype <Beast> { public Beast (Beast source) {} }public class OrcBeast extends Beast { private final String weapon; public OrcBeast (OrcBeast orcBeast) { super (orcBeast); this .weapon = orcBeast.weapon; } @Override public String toString () { return "Orcish wolf attacks with " + weapon; } }
不同原型的工厂
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public interface HeroFactory { Mage createMage () ; Warlord createWarlord () ; Beast createBeast () ; }@RequiredArgsConstructor public class HeroFactoryImpl implements HeroFactory { private final Mage mage; private final Warlord warlord; private final Beast beast; public Mage createMage () { return mage.copy(); } public Warlord createWarlord () { return warlord.copy(); } public Beast createBeast () { return beast.copy(); } }
应用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public static void main (String[] args) { var factory = new HeroFactoryImpl ( new ElfMage ("cooking" ), new ElfWarlord ("cleaning" ), new ElfBeast ("protecting" ) ); var mage = factory.createMage(); var warlord = factory.createWarlord(); var beast = factory.createBeast(); LOGGER.info(mage.toString()); LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); factory = new HeroFactoryImpl ( new OrcMage ("axe" ), new OrcWarlord ("sword" ), new OrcBeast ("laser" ) ); mage = factory.createMage(); warlord = factory.createWarlord(); beast = factory.createBeast(); LOGGER.info(mage.toString()); LOGGER.info(warlord.toString()); LOGGER.info(beast.toString()); }
输出
1 2 3 4 5 6 08:36:19.012 [main] INFO com.iluwatar.prototype.App -- Elven mage helps in cooking 08:36:19.013 [main] INFO com.iluwatar.prototype.App -- Elven warlord helps in cleaning 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Elven eagle helps in protecting 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish mage attacks with axe 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish warlord attacks with sword 08:36:19.014 [main] INFO com.iluwatar.prototype.App -- Orcish wolf attacks with laser
注意
需要深拷贝,原型对象的属性又非常复杂的场景,原型模式实现克隆可能会比较复杂
可能出现循环引用的问题
设计模式之原型模式
http://s1mplecode.com/design-pattern/prototype.html