设计模式——抽象工厂模式
程序员文章站
2022-11-05 11:08:09
抽象工厂方法_将关联组件组装成产品 附录 https://github.com/maikec/pattern 个人GitHub设计模式案例 声明 引用该文档请注明出处 ......
抽象工厂方法_将关联组件组装成产品
** * 印刷抽象工厂类 * @author maikec * 2019/5/20 */ public abstract class abstractprintingfactory { private static abstractprintingfactory ourinstance ; /** * 获取工厂实例 * @param classname 工厂类类名 * @return */ public static abstractprintingfactory getinstance(string classname) { if (null == ourinstance){ reentrantreadwritelock.writelock writelock = new reentrantreadwritelock().writelock(); if (writelock.trylock()){ if (null == ourinstance){ try { ourinstance = (abstractprintingfactory) class.forname(classname).newinstance(); } catch (instantiationexception | illegalaccessexception | classnotfoundexception e) { e.printstacktrace(); } } } } return ourinstance; } /** * 生产纸 * @return */ public abstract basepaper createpaper(); /** * 生成颜料 * @return */ public abstract basepigment createpigment(); /** * @param paper * @param pigment * 生成图画 * @return */ public abstract basedrawing createdrawing(basepaper paper, basepigment pigment); } /** * 图画 * @author maikec * 2019/5/20 */ @allargsconstructor public abstract class basedrawing { protected basepaper paper; protected basepigment pigment; @getter private string name; } /** * 纸 * @author maikec * 2019/5/20 */ @getter @setter public abstract class basepaper { protected string name; } /** * 颜料 * @author maikec * @date 2019/5/12 */ @getter @setter public abstract class basepigment { protected string name; } /** * 默认印刷工厂类 * @author maikec * @date 2019/5/12 */ public class defaultprintingfactory extends abstractprintingfactory { public defaultprintingfactory(){ super(); }; @override public basepaper createpaper() { basepaper paper = defaultpaper.builder().build(); paper.setname("defaultpaper"); return paper; } @override public basepigment createpigment() { basepigment pigment = defaultpigment.builder().build(); pigment.setname("defaultpigment"); return pigment; } @override public basedrawing createdrawing(basepaper paper, basepigment pigment) { return new defaultdrawing(paper,pigment,"defaultdrawing"); } } /** * @author maikec * 2019/5/20 */ public class defaultdrawing extends basedrawing { public defaultdrawing(basepaper paper, basepigment pigment,string name) { super(paper, pigment,name); } } /** * 默认纸 * @author maikec * 2019/5/20 */ @builder public class defaultpaper extends basepaper { } /** * @author maikec * @date 2019/5/12 */ @builder public class defaultpigment extends basepigment { } /** * @author maikec * @date 2019/5/12 */ public class abstractfactorydemo { public static void main(string[] args) { abstractprintingfactory instance = defaultprintingfactory.getinstance(defaultprintingfactory.class.getname()); basepaper paper = instance.createpaper(); basepigment pigment = instance.createpigment(); system.out.println(instance.createdrawing(paper, pigment).getname()); } }
附录
https://github.com/maikec/pattern 个人github设计模式案例
声明
引用该文档请注明出处
上一篇: 致python初学者的天梯