2普通工厂方法模式
就是建立一个工厂类,对实现了同一接口的一些类进行实例的创建。
2.1创建接口
1 /** 2 * 发送接口 3 * Created by mrf on 2016/2/25. 4 */ 5 public interface Sender { 6 public String send(); 7 }
2.2创建两个实现
1 /** 2 * 邮件发送 3 * Created by mrf on 2016/2/25. 4 */ 5 public class MailSender implements Sender { 6 @Override 7 public String send() { 8 System.out.println("This is emailSender!");
return "email"; 9 } 10 } 11 12 /** 13 * 短信发送 14 * Created by mrf on 2016/2/25. 15 */ 16 public class SmsSender implements Sender { 17 @Override 18 public String send() { 19 System.out.println("This is SmsSender!!");return "sms"; 20 } 21 }
2.3创建工厂
1 /** 2 * 发送工厂 3 * Created by mrf on 2016/2/25. 4 */ 5 public class SendFactory { 6 7 public Sender produce(String type){ 8 if("email".equals(type)){ 9 return new MailSender(); 10 } 11 if ("sms".equals(type)){ 12 return new SmsSender(); 13 } 14 System.out.println("输入类型不正确!"); 15 return null; 16 } 17 }
2.4使用测试
SendFactoryTest {
protected long startTime;
protected long endTime;
@Before
public void setUp() throws Exception {
this.startTime= System.currentTimeMillis();
System.out.println("=========开始测试===========");
}
@After
public void tearDown() throws Exception {
this.endTime = System.currentTimeMillis();
System.out.println("测试用时:"+(endTime-startTime));
System.out.println("=========测试结束===========");
}
@Test
public void testProduce() throws Exception {
SendFactory sendFactory = new SendFactory();
Sender sender = sendFactory.produce("email");
String send = sender.send();
} }
2.5多个工厂方法模式
package com.test.java.designPattern.factory; /** * 多个工厂模式 * <p> * 是对普通工厂方法模式的改进。因为普通方法模式中key错误则不能正确创建对象, * 多个工厂模式提供多个创建方法。 * </p> * Created by mrf on 2016/2/26. */ public class MultiSendFacoty { public Sender produceMail(){ return new MailSender(); } public Sender produceSms(){ return new SmsSender(); } }
测试:
package com.test.java.designPattern.factory; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by mrf on 2016/2/26. */ public class MultiSendFacotyTest { private MultiSendFacoty facoty; @Before public void setUp(){ facoty = new MultiSendFacoty(); } @Test public void testProduceMail() throws Exception { Sender sender = facoty.produceMail(); sender.send(); } @Test public void testProduceSms() throws Exception { Sender sender = facoty.produceSms(); sender.send(); } }