每日随笔——抽象工厂模式
[实验任务一]:人与肤色
使用抽象工厂模式,完成下述产品等级结构:
实验要求:
1.画出对应的类图;
2.提交源代码;
3.注意编程规范。
1、类图
2、 源码
BlackFactory
package sc4; public class BlackFactory implements MWFactory { public static Man produceMan() { return new BlackSkinMan(); } public static Woman produceWomen() { return new BlackSkinWomen(); } } BlackSkinMan
package sc4; public class BlackSkinMan implements Man { public void play() { System.out.println("我是黑种男人!"); } } BlackSkinWomen
package sc4; public class BlackSkinWomen implements Woman { public void play() { System.out.println("我是黑种女人!"); } } client
package sc4; import java.util.Scanner; public class Client { public static void main(String args[]) { Man m; Woman w; Scanner x = new Scanner(System.in); int n = 0; System.out.println("请选择肤色 1.黑色,2、白色,3、黄色"); if (x.hasNextInt()) { n = x.nextInt(); } else { System.out.println("输入的不是整数,请重新输入:"); } switch (n) { case 1: { m = BlackFactory.produceMan(); m.play(); w = BlackFactory.produceWomen(); w.play(); break; } case 2: { m = WhiteFactory.produceMan(); m.play(); w = WhiteFactory.produceWomen(); w.play(); break; } case 3: { m = YellowFactory.produceMan(); m.play(); w = YellowFactory.produceWomen(); w.play(); break; } } } } Man
package sc4; public interface Man { public void play(); } MWFactory
package sc4; public interface MWFactory { public static Man produceMan() { return null; } public static Woman produceWomen() { return null; } } WhiteFactory
package sc4; public class WhiteFactory implements MWFactory { public static Man produceMan() { return new WhiteSkinMan(); } public static Woman produceWomen() { return new WhiteSkinWomen(); } } WhiteSkinMan
package sc4; public class WhiteSkinMan implements Man{ public void play() { System.out.println("我是白种男人!"); } } WhiteSkinWomen
package sc4; public class WhiteSkinWomen implements Woman{ public void play() { System.out.println("我是白种女人!"); } } Woman
package sc4; public interface Woman { public void play(); }
YellowFactory
package sc4; public class YellowFactory { public static Man produceMan() { return new YellowSkinMan(); } public static Woman produceWomen() { return new YellowSkinWomen(); } } yellowSkinMan
package sc4; public class YellowSkinMan implements Man{ public void play() { System.out.println("我是黄种男人!"); } }
yellowSkinWomen package sc4; public class YellowSkinWomen implements Woman{ public void play() { System.out.println("我是黄种女人!"); } }