設計模式之普通工廠模式
1. 工廠模式
工廠模式分為三種
(1.)普通工廠模式
普通工廠模式,就是建立一個工廠類,對實現了同一個接口的一些類進行實例的創建。
普通工廠模式關系圖
以下舉例:(我們舉一個發送郵件和短信的例子)
首先,創建二者的共同接口:
[java] view plaincopy
public interface Sender {
public void Send();
}
其次,創建實現類:
[java] view plaincopy
實現類一
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
[java] view plaincopy
實現類二
public class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
最後,建工廠類:
[java] view plaincopy
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!
設計模式之普通工廠模式