给系统带来更大的可拓展性和更少的修改量。把父类和子类都统一起来,在工厂里面实例化对象。
package 工厂模式; public class Test { public static void main(String[] args) { Computer deskComputer = Factory.getComputer("DeskComputer", "华硕", "16G"); Computer nodebookComputer = Factory.getComputer("NodebookComputer", "联想", "8G"); Computer pad = Factory.getComputer("Pad", "苹果", "4G"); deskComputer.run(); nodebookComputer.run(); pad.run(); Computer comTest = Factory.getComputer("phone", "宏碁", "2G"); } }
package 工厂模式; public abstract class Computer { public String type; public String size; public abstract void run(); }
package 工厂模式; public class DeskComputer extends Computer{ public DeskComputer(String type,String size){ super.size = size; super.type = type; } public void run() {//子类重写父类构造方法,面向对象多态的体现 System.out.println("DeskComputer是"+type+"牌子"+size+"体验很好"); } }
package 工厂模式; public class NodebookComputer extends Computer{ public NodebookComputer(String type,String size){ super.size = size; super.type = type; } public void run() {//子类重写父类构造方法,面向对象多态的体现 System.out.println("NodebookComputer是"+type+"牌子"+size+"运行不错"); } }
package 工厂模式; public class Pad extends Computer{ public Pad(String type,String size){ super.size = size; super.type = type; } public void run() { System.out.println("Pad是"+type+"牌子"+size+"轻巧方便"); } }
package 工厂模式; public class Factory { public static Computer getComputer(String model,String type,String size){ Computer com = null; if(model.equals("DeskComputer")){ com = new DeskComputer(type,size); }else if(model.equals("NodebookComputer")){ com = new NodebookComputer(type,size); }else if(model.equals("Pad")){ com = new Pad(type,size); }else{ System.out.println("输入类型不正确,工厂无法创建对象......"); } return com; } }