二十三种设计模式1.2 多个工厂方法模式

本文详细介绍了多个工厂方法模式的概念及其实现方式,通过对比普通工厂方法模式,突出了其在错误处理和对象创建上的优势。并通过具体代码示例展示了如何使用多个工厂方法来创建不同类型的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

将上面的代码做下修改,改动下SendFactory类就行,如下:

1. public class SendFactory {  
2.   public Sender produceMail(){  
3.         return new MailSender();  
4.     }  
5.       
6.   public Sender produceSms(){  
7.         return new SmsSender();  
8.    }  
9. } 

测试类如下:

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!

该文章并非原创但年代久远真实作者无法考证,只做整理以备查阅,在此向原作者致敬!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值