標籤:interface java學習 public
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 sendthis 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 sendthis is Sms Send====================
以上在實現原廠模式時,只需要新增介面就能在不改變原始碼的情況下,輕鬆的拓展新的介面
原廠模式適用於有大量產品需要建立,但是又有共同介面時使用
JAVA學習筆記-----設計模式之原廠模式