简单工厂模式的java实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package she.ji.mo.shi; 2 3 /** 4 * @author hanxin 5 * 标题:简单工厂模式 6 * 功能:客户端只需要知道父类和工厂类,不需要知道具体实现的子类,对客户端屏蔽了实现的细节,解了一定的耦合。 7 * 如何扩展:添加Father的子类,并在SimpleFactory类里的switch函数里添加case语句 8 */ 9 public class Client { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 Father fa=SimpleFactory.getFather(2); 14 fa.sayHello();//实际调用的是Children2的方法 15 } 16 17 } 18 class SimpleFactory 19 { 20 public static Father fa; 21 public static Father getFather(int i) 22 { 23 switch (i) 24 { 25 case 1: 26 fa=new Children1();//通过父类的变量,指向子类的对象,从而可以调用子类与父类同名方法的不同实现 27 break; 28 case 2: 29 fa=new Children2(); 30 break; 31 } 32 return fa; 33 } 34 } 35 class Father 36 { 37 public void sayHello() 38 { 39 System.out.println("Father say Hello"); 40 } 41 } 42 class Children1 extends Father 43 { 44 public void sayHello() 45 { 46 System.out.println("Children1 say Hello"); 47 } 48 } 49 class Children2 extends Father 50 { 51 public void sayHello() 52 { 53 System.out.println("Children2 say Hello"); 54 } 55 }
可以将代码中的类,都放在同一个包下的不同的java文件里--Client称客户端就更明了。
欢迎一起讨论设计模式。比如某个模式的优缺点,适合什么情况下使用等等。
小小程序员--一直很安静的我。