工廠模式(Factory Method)分為三種 :簡(jiǎn)單工廠模式耘眨、多個(gè)工廠方法模式臭埋、抽象工廠模式(Abstract Factory)
1.1簡(jiǎn)單工廠模式:就是建立一個(gè)工廠類奴艾,對(duì)實(shí)現(xiàn)了同一個(gè)接口類進(jìn)行實(shí)例的創(chuàng)建顾画。
/**
* 具有發(fā)送功能
*/
public interface Sender {
void send();
}
/**
* 具有發(fā)送短信功能
*/
public class SmsSender implements Sender {
@Override
public void send() {
System.out.print("This is Sms Sender");
}
}
/**
* 具有發(fā)送郵件功能
*/
public class MailSender implements Sender {
@Override
public void send() {
System.out.print("This is email send");
}
}
/**
* 簡(jiǎn)單工廠類的創(chuàng)建齐媒,根據(jù)不同類型創(chuàng)建實(shí)例滨砍。
*/
public class SendFactory {
public Sender produce(String type){
if("email".equals(type)){
return new SmsSender();
}else if("Sms".equals(type)){
return new MailSender();
}
return null;
}
}