工厂方法模式(选自《设计模式之禅》)
人类接口:
public interface Human { // 每个人种的皮肤都有相应的颜色 public void getColor(); // 人类会说话 public void talk(); }
黑色人种:
public class BlackHuman implements Human { @Override public void getColor() { System.out.println("黑色人种皮肤是黑色!"); } @Override public void talk() { System.out.println("黑人会说话,一般人听不懂!"); } }
黄色人种:
public class YellowHuman implements Human { @Override public void getColor() { System.out.println("黄色人种皮肤是黄色!"); } @Override public void talk() { System.out.println("黄色人种会说话,一般说的都是双字节!"); } }
白色人种:
public class WhiteHuman implements Human { @Override public void getColor() { System.out.println("白色人种皮肤是白色!"); } @Override public void talk() { System.out.println("白色人种会说话,一般都是单字节!"); } }
抽象工厂类:
public abstract class AbstractHumanFactory { public abstract <T extends Human> T createHuman(Class<T> c); }
具体工厂类:
public class HumanFactory extends AbstractHumanFactory { @Override public <T extends Human> T createHuman(Class<T> c) { Human human = null; try { human = (Human) Class.forName(c.getName()).newInstance(); } catch (Exception e) { System.out.println("人种生成错误!"); } return (T) human; } }
女娲造人:
public class NvWa { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub AbstractHumanFactory yinYangLu = new HumanFactory(); System.out.println("造出的第一批人是白色人种!"); Human whilteHuman = yinYangLu.createHuman(WhiteHuman.class); whilteHuman.getColor(); whilteHuman.talk(); System.out.println("造出的第二批人是黑色人种!"); Human blackHuman = yinYangLu.createHuman(BlackHuman.class); blackHuman.getColor(); blackHuman.talk(); System.out.println("造出的第三批人是黄色人种!"); Human yellowHuman = yinYangLu.createHuman(YellowHuman.class); yellowHuman.getColor(); yellowHuman.talk(); } }