Java简单的工厂模式例子:
//工厂类 class ActionFactory{ //获取对应的实体类 public static Action getAction(int type){ if (0 == type){ return new DogAction(); }else { return new CatAction(); } } } //接口 interface Action{ void doSamthing(); } class DogAction implements Action{ @Override public void doSamthing() { System.out.println("狗吃猪肉"); } } class CatAction implements Action{ @Override public void doSamthing() { System.out.println("猫吃鱼肉"); } }
调用:
Action action = ActionFactory.getAction(0); action.doSamthing();