java-工厂
class Mouse{ public void sayHi(){}; } class DellMouse extends Mouse { @Override public void sayHi() { System.out.println("产品:戴尔鼠标"); } } class HpMouse extends Mouse { @Override public void sayHi() { System.out.println("产品:惠普鼠标"); } } class KeyBoard { public void kick(){}; } class HpKeyBoard extends KeyBoard { @Override public void kick() { System.out.println("产品:惠普键盘"); } } class DellKeyBoard extends KeyBoard { @Override public void kick() { System.out.println("产品:戴尔键盘"); } } //总的工厂接口 interface PcFactory { public Mouse createMouse() ; public KeyBoard createKeyBoard() ; } class HpFactory implements PcFactory { @Override public Mouse createMouse() { return new HpMouse(); } @Override public KeyBoard createKeyBoard() { return new HpKeyBoard(); } } class DellFactory implements PcFactory { @Override public Mouse createMouse() { return new DellMouse(); } @Override public KeyBoard createKeyBoard() { return new DellKeyBoard(); } } //当需要增加一个华硕工厂时: class AsusMouse extends Mouse { @Override public void sayHi() { System.out.println("产品:华硕鼠标"); } } class AsusKeyBoard extends KeyBoard { @Override public void kick() { System.out.println("产品:华硕键盘"); } } class AsusFactory implements PcFactory { @Override public Mouse createMouse() { return new AsusMouse(); } @Override public KeyBoard createKeyBoard() { return new AsusKeyBoard(); } } public class NormFactory { public static void main(String[] args) { PcFactory hpFact = new HpFactory(); Mouse hpm = hpFact.createMouse(); KeyBoard hpkbd = hpFact.createKeyBoard(); PcFactory dellFact = new DellFactory(); Mouse dellm = dellFact.createMouse(); KeyBoard dellkbd = dellFact.createKeyBoard(); hpm.sayHi(); dellm.sayHi(); hpkbd.kick(); dellkbd.kick(); } }
打印结果如下:
产品:惠普鼠标 产品:戴尔鼠标 产品:惠普键盘 产品:戴尔键盘