java学习笔记-设计模式3(工厂模式)

意图:

  定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。

适用性
  当一个类不知道它所必须创建的对象的类的时候。
  当一个类希望由它的子类来指定它所创建的对象的时候。
  当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
 
1 public interface Sender {  
2     public void Send();  
3 }
1 public class MailSender implements Sender {  
2     @Override  
3     public void Send() {  
4         System.out.println("this is mailsender!");  
5     }  
6 }
1 public class SmsSender implements Sender {  
2     @Override  
3     public void Send() {  
4         System.out.println("this is sms sender!");  
5     }  
6 }
 1 //
 2 public class SendFactory { 
 3      // 普通工厂模式
 4      public Sender produce(String type) {  
 5          if ("mail".equals(type)) {  
 6              return new MailSender();  
 7          } else if ("sms".equals(type)) {  
 8              return new SmsSender();  
 9          } else {  
10              System.out.println("请输入正确的类型!");  
11              return null;  
12          }  
13      } 
14 
15       // 多个工厂方法模式
16      public Sender produceMail() {  
17              return new MailSender();    
18      } 
19      public Sender produceSms() {  
20              return new SmsSender();    
21      } 
22 
23       // 静态工厂方法模式
24      public static Sender produceMail() {  
25              return new MailSender();    
26      } 
27      public static Sender produceSms() {  
28              return new SmsSender();    
29      } 
30 }

 总体来说,工厂模式适合:凡是出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。

  转自:http://blog.csdn.net/zhangerqing/article/details/8194653

     Gof设计模式 中文版

原文地址:https://www.cnblogs.com/gxl00/p/5012896.html