1.设计模式---------->工厂模式:
Sender.java
package me.ele.mytest;
public interface Sender
{
public void send();
}2.MailSend
package me.ele.mytest;
public class MailSend implements Sender
{
@Override
public void send()
{
System.out.println("this is mail send");
}
}3.SmsSend
package me.ele.mytest;
public class SmsSend implements Sender
{
@Override
public void send()
{
System.out.println("this is Sms Send");
}
}4.TestFactory
package me.ele.mytest;
public class TestFactory {
public Sender produce(String type) {
if (type.equals("Mail")) {
return new MailSend();
} else if (type.equals("Sms")) {
return new SmsSend();
} else {
System.out.println("请输入正确的类型");
return null;
}
}
}5.Main.java
package me.ele.mytest;
public class Main {
public static void main(String[] args)
{
System.out.println("开始测试工厂设计模式");
System.out.println("====================");
TestFactory t = new TestFactory();
Sender s1 = t.produce("Mail");
Sender s2 = t.produce("Sms");
s1.send();
s2.send();
System.out.println("====================");
}
}6. result
开始测试工厂设计模式 ==================== this is mail send this is Sms Send ====================
7.以上的模式使用起来需要匹配字符,较为不便.可以使用抽象工厂模式来使用
新增Provider接口
package me.ele.mytest;
public interface Provider {
public Sender produce();
}新增实现Provider接口的SendMailFactory与SendSmsFactory类
package me.ele.mytest;
public class SendMailFactory implements Provider {
@Override
public Sender produce(){
return new MailSend();
}
}package me.ele.mytest;
public class SendSmsFactory implements Provider{
@Override
public Sender produce(){
return new SmsSend();
}
}修改Main方法:
package me.ele.mytest;
public class Main {
public static void main(String[] args)
{
System.out.println("开始测试工厂设计模式");
System.out.println("====================");
Provider s1 = new SendMailFactory();
Provider s2 = new SendSmsFactory();
s1.produce().send();
s2.produce().send();
System.out.println("====================");
}
}返回结果
开始测试工厂设计模式 ==================== this is mail send this is Sms Send ====================
以上在实现工厂模式时,只需要新增接口就能在不改变源代码的情况下,轻松的拓展新的接口
工厂模式适用于有大量产品需要创建,但是又有共同接口时使用
原文:http://warcraft3.blog.51cto.com/6514883/1875396