java email工厂_JAVA学习笔记-----设计模式之工厂模式

1.设计模式---------->工厂模式:

Sender.javapackage me.ele.mytest;

public interface Sender

{

public void send();

}

2.MailSendpackage me.ele.mytest;

public class MailSend implements Sender

{

@Override

public  void send()

{

System.out.println("this is mail send");

}

}

3.SmsSendpackage me.ele.mytest;

public class SmsSend implements Sender

{

@Override

public  void send()

{

System.out.println("this is Sms Send");

}

}

4.TestFactorypackage 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.javapackage 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

====================

以上在实现工厂模式时,只需要新增接口就能在不改变源代码的情况下,轻松的拓展新的接口

工厂模式适用于有大量产品需要创建,但是又有共同接口时使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值