1.普通工廠模式:
建立一個(gè)工廠類(lèi)解寝,對(duì)實(shí)現(xiàn)了同一接口的一些類(lèi)進(jìn)行實(shí)例的創(chuàng)建。
例子:
public interface Sender {
public void Send();
}
public class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mailsender!");
}
}
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("請(qǐng)輸入正確的類(lèi)型!");
return null;
}
}
}
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender = factory.produce("sms");
sender.Send();
}
}
2.多個(gè)工廠方法模式
普通工廠方法模式的改進(jìn),提供多個(gè)工廠方法,分別創(chuàng)建對(duì)象
將上面的代碼做下修改乘粒,改動(dòng)下SendFactory類(lèi)就行膨更,如下:
public class SendFactory {
public Sender produceMail(){
return new MailSender();
}
public Sender produceSms(){
return new SmsSender();
}
}
public class FactoryTest {
public static void main(String[] args) {
SendFactory factory = new SendFactory();
Sender sender1 = factory.produceMail();
Sender sender2 = factory.produceSms();
sender1.Send();
sender2.Send();
}
}
3.靜態(tài)工廠方法模式
上面的多個(gè)工廠方法模式里的方法置為靜態(tài)的,不需要?jiǎng)?chuàng)建實(shí)例注祖,直接調(diào)用即可
將上面的代碼做下修改猾蒂,改動(dòng)下SendFactory類(lèi)就行,如下:
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();
}
}