當(dāng)前位置:
首頁(yè) >
每天一个设计模式,工厂方法模式(Factory Method)
發(fā)布時(shí)間:2025/4/9
50
豆豆
生活随笔
收集整理的這篇文章主要介紹了
每天一个设计模式,工厂方法模式(Factory Method)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
普通工廠模式:就是建立一個(gè)工廠類,對(duì)實(shí)現(xiàn)了同一接口的一些類進(jìn)行實(shí)例的創(chuàng)建:關(guān)系圖如下:
1.創(chuàng)建共同的接口
public interface Sender { public void Send(); }2.創(chuàng)建該接口的實(shí)現(xiàn)類
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!"); } }3.建立工廠類
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)輸入正確的類型!"); return null; } } }4.測(cè)試
public class FactoryTest { public static void main(String[] args) { SendFactory factory = new SendFactory(); Sender sender = factory.produce("sms"); sender.Send(); } }輸出:this is mailsender!
轉(zhuǎn)載于:https://www.cnblogs.com/fenghx/p/9497688.html
總結(jié)
以上是生活随笔為你收集整理的每天一个设计模式,工厂方法模式(Factory Method)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 潭州Java中级班(day_04)
- 下一篇: 设计模式学习---策略模式