publicabstractclassProduct{protectedvoidmade(){System.out.println(getClass().getSimpleName()+" has been made");}protectedvoidsold(){System.out.println(getClass().getSimpleName()+" has been sold");}}publicclassCanextendsProduct{@Overridepublicvoidmade(){super.made();}@Overridepublicvoidsold(){super.sold();}}publicclassToyextendsProduct{@Overridepublicvoidmade(){super.made();}@Overridepublicvoidsold(){super.sold();}}
publicabstractclassFactory{privateProductproduct;// 引用抽象的产品类publicFactory(Productp){this.product=p;}publicvoidmakeMoney(){product.made();product.sold();}}publicclassCanFactoryextendsFactory{// 只接受Can类publicCanFactory(Canp){super(p);}@OverridepublicvoidmakeMoney(){super.makeMoney();System.out.println(getClass().getSimpleName()+" make money!");}}publicclassModernFactoryextendsFactory{// 只要是Product即可生产publicModernFactory(Productp){super(p);}@OverridepublicvoidmakeMoney(){super.makeMoney();System.out.println("ModernFactory make money!");}}
Cancan=newCan();CanFactorycanFactory=newCanFactory(can);canFactory.makeMoney();ModernFactorymodernFactory=newModernFactory(newToy());modernFactory.makeMoney();/*Can has been madeCan has been soldCanFactory make money!Toy has been madeToy has been soldModernFactory make money!*/