java设计模式学习 ----- 工厂方法模式(Factory Method)

工厂方法模式(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.   
  3.     @Override  
  4.     public void Send() {  
  5.         System.out.println("this is sms sender!");  
  6.     }  
  7. }  

最后。建工厂类:

  1. public class SendFactory {  
  2.   
  3.     public Sender produce(String type) {  
  4.         if ("mail".equals(type)) {  
  5.             return new MailSender();  
  6.         } else if ("sms".equals(type)) {  
  7.             return new SmsSender();  
  8.         } else {  
  9.             System.out.println("请输入正确的类型!");  
  10.             return null;  
  11.         }  
  12.     }  
  13. }  

我们来測试下:

  1. public class FactoryTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         SendFactory factory = new SendFactory();  
  5.         Sender sender = factory.produce("sms");  
  6.         sender.Send();  
  7.     }  
  8. }  

输出:this is sms sender!


多个工厂方法模式,是对普通工厂方法模式的改进。在普通工厂方法模式中,假设传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。关系图:

将上面的代码做下修改。修改下SendFactory类即可。例如以下:

[java] view plaincopypublic class SendFactory {  
   public Sender produceMail(){  
  1.         return new MailSender();  
  2.     }  
  3.       
  4.     public Sender produceSms(){  
  5.         return new SmsSender();  
  6.     }  
  7. }  

測试类例如以下:

  1. public class FactoryTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         SendFactory factory = new SendFactory();  
  5.         Sender sender = factory.produceMail();  
  6.         sender.Send();  
  7.     }  
  8. }  

输出:this is mailsender!


静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的。不须要创建实例,直接调用即可。

  1. public class SendFactory {  
  2.       
  3.     public static Sender produceMail(){  
  4.         return new MailSender();  
  5.     }  
  6.       
  7.     public static Sender produceSms(){  
  8.         return new SmsSender();  
  9.     }  
  10. }  
  1. public class FactoryTest {  
  2.   
  3.     public static void main(String[] args) {      
  4.         Sender sender = SendFactory.produceMail();  
  5.         sender.Send();  
  6.     }  
  7. }  

输出:this is mailsender!


总结。工厂模式适合:凡是出现了大量的产品须要创建,而且具有共同的接口时,能够通过工厂方法模式进行创建。在以上的三种模式中,第一种假设传入的字符串有误,不能正确创建对象,第三种相对于另外一种,不须要实例化工厂类,所以,大多数情况下,会选用第三种 —— 静态工厂方法模式。



原文地址:https://www.cnblogs.com/jzssuanfa/p/7307096.html