设计模式之创建型模式---工厂模式

工厂模式(Factory Method)
工厂模式分为三种:
1、普通工厂模式
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。举例如下:例如,QQ和微信都有发消息的功能,首先,我们创建二者共同的发消息接口:

  1. public interface SendNotifaction{
  2. public void Send();  
    
  3. }

接着创建实现类:

  1. public class QQ implements SendNotifaction{

  2. @Override  
    
  3. public void Send() {  
    
  4.     System.out.println("i am a boy!");  
    
  5. }  
    
  6. }

  7. public class WeChat implements SendNotifaction{

  8. @Override  
    
  9. public void Send() {  
    
  10.     System.out.println("i am a girl!");  
    
  11. }  
    
  12. }
    最后,我们开始来创建工厂类:

  13. public class SendNotifactionFactory {

  14. public Sender produce(String type) {  
    
  15.     if ("qq".equals(type)) {  
    
  16.         return new QQ ();  
    
  17.     } else if ("wechat".equals(type)) {  
    
  18.         return new WeChat ();  
    
  19.     } else {  
    
  20.         System.out.println("please input right type!");  
    
  21.         return null;  
    
  22.     }  
    
  23. }  
    
  24. }
    测试如下:

  25. public class FactoryTest {

  26. public static void main(String[] args) {  
    
  27.     SendNotifactionFactory factory = new SendNotifactionFactory ();  
    
  28.     SendNotifaction senderNotifaction = factory.produce("qq");  
    
  29.     senderNotifaction .Send();  
    
  30. }  
    
  31. }
    控制台打印:i am a boy!

2、多个工厂方法模式
这种模式是对普通工厂方法模式的改进,提供多个工厂方法创建实例.将上面的代码做下修改,改动下SendNotifactionFactory 类就行,如下:
public class SendNotifactionFactory {
public SendNotifactionproduce QQ(){

  1.     return new QQ ();  
    
  2. }  
    
  3. public SendNotifactionproduce Wechat(){  
    
  4.     return new WeChat ();  
    
  5. }  
    
  6. }
    测试类如下:

  7. public class FactoryTest {

  8. public static void main(String[] args) {  
    
  9.     SendNotifactionFactory  factory = new SendNotifactionFactory ();  
    
  10.     SendNotifaction senderNotifaction = factory.QQ();  
    
  11.     senderNotifaction .Send();  
    
  12. }  
    
  13. }
    控制台打印:i am a boy!
    3、静态工厂方法模式
    将上面的多个工厂方法模式里的方法置改为静态的,直接调用即可。

  14. public class SendFactory {

  15. public static SendNotifactionproduce QQ(){  
    
  16.     return new QQ();  
    
  17. }  
    
  18. public static SendNotifactionproduce Wechat(){  
    
  19.     return new Wechat();  
    
  20. }  
    
  21. }

  22. public class FactoryTest {

  23. public static void main(String[] args) {     
    
  24.     SendNotifaction senderNotifaction = SendNotifactionFactory .QQ();  
    
  25.     sender.Send();  
    
  26. }  
    
  27. }
    控制台打印:i am a boy!
    总结:
    工厂模式的应用场景:凡是出现了大量的实例需要创建,并且这些实例具有共同的接口时,就可以运用工厂模式进行创建。在以上的三种模式中,第一种如果传入的参数有误,则不能正确创建对象,第二种需要实例化工厂,浪费没必要的内存性能,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值