介紹工廠模式
原文:https://blog.csdn.net/llussize/article/details/80276627
定義一個創建對象的接口,讓其子類自己決定實例化哪一個工廠類,工廠模式使其創建過程延遲到子類進行。
類圖
簡單工廠模式:
舉例如下:
1.創建一個發送的接口
public interface Sender {
public void Send();
}
2.創建兩個類實現它
//第一種採用email發送
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mail sender!");
}
}
//第二種採用短信方式發送
public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
此處創建工廠,判斷調用者使用哪種方式
public class SendFactory {
public Sender produce(String type) {
if ("mail".equals(type)) {
return new MailSender();
} else if ("sms".equals(type)) {
return new SmsSender();
} else {
System.out.println("請輸入正確的類型!");
return null;
}
}
}
這就相當於一個工廠有兩條生產線,一個生產用郵件發送方式,另一個生產採用短信發送方式
最後調用者調用工廠,來生產
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produce("sms");
sender.Send();
}
}
輸出結果:this is sms sender!
補充:靜態工廠方法模式,工廠方法模式裏的方法置爲靜態的,不需要創建實例,直接調用即可。
public class SendFactory {
public static Sender produceMail(){
return new MailSender();
}
public static Sender produceSms(){
return new SmsSender();
}
}
public class FactoryTest {
public static void main(String[] args) {
Sender sender = SendFactory.produceMail();
sender.Send();
}
}
輸出:this is mailsender!
總體來說,工廠模式適合:凡是出現了大量的產品需要創建,並且具有共同的接口時,可以通過工廠方法模式進行創建。大多數情況下,我們會選用靜態工廠方法模式。