设计模式-简单工厂模式

来源:互联网 发布:mac本地播放器 编辑:程序博客网 时间:2024/05/22 14:03

简单工厂模式又名静态方法工厂模式,由一个工厂对象决定创建哪一个产品的实例 使用场景:客户端需要创建对象,隐藏对象的创建过程,并且目标对象类型数量不是很多的时候,可以考虑使用简单工厂模式 Product 产品的通用接口,用来定义产品的行为 ConcreteProduct 具体的产品,实现了Product接口Creater 工厂类,通过factory来创建对象优点:分工明确,各司其职客户端不再创建对象,而是把创建对象的职责交给了具体的工厂去创建使抽象与实现分离,客户端不知道具体的实现过程具名工厂函数,更能体现代码的含义缺点:工厂的静态方法无法被继承代码维护不易,要是对象很多的话,工厂类会很庞大违反开闭原则,如果有新的产品加入系统中就要修改工厂类

package com.lantier.xxb_student.drawlayerlayout.iphone;/** * Created by xxb_student on 2017/5/20. */public interface Iphone {    static final String TAG = "Iphone";    void call();    void sendMessage();    void getNetWork();}



package com.lantier.xxb_student.drawlayerlayout.iphone;import android.util.Log;/** * Created by xxb_student on 2017/5/20. */public class Iphone4s implements Iphone {    private static final String TAG = "Iphone4s";    @Override    public void call() {        Log.d(TAG, "---->>call: Iphone4s");    }    @Override    public void sendMessage() {        Log.d(TAG, "---->>sendMessage:Iphone4s ");    }    @Override    public void getNetWork() {        Log.d(TAG, "---->>getNetWork: Iphone4s");    }}



package com.lantier.xxb_student.drawlayerlayout.iphone;import android.util.Log;/** * Created by xxb_student on 2017/5/20. */public class Iphone5s implements Iphone {    private static final String TAG = "Iphone5s";    @Override    public void call() {        Log.d(TAG, "---->>call: Iphone5s");    }    @Override    public void sendMessage() {        Log.d(TAG, "---->>sendMessage: Iphone5s");    }    @Override    public void getNetWork() {        Log.d(TAG, "---->>getNetWork: Iphone5s");    }}



package com.lantier.xxb_student.drawlayerlayout.iphone;/** * Created by xxb_student on 2017/5/20. */public final class IphoneFactory {    public static Iphone createIphone( String type){        if (type == null){            return null;        }        Iphone iphone = null;        if (type.equals("Iphone4s")){            iphone = new Iphone4s();        } else if (type.equals("Iphone5s")){            iphone = new Iphone5s();        }        return iphone;    }}


最后的log:

Iphone iphone4s = IphoneFactory.createIphone("Iphone4s");iphone4s.sendMessage();Iphone iphone5s = IphoneFactory.createIphone("Iphone5s");iphone5s.call();
05-20 11:45:50.554 20843-20843/com.lantier.xxb_student.drawlayerlayout D/Iphone4s: ---->>sendMessage:Iphone4s 
05-20 11:45:50.555 20843-20843/com.lantier.xxb_student.drawlayerlayout D/Iphone5s: ---->>call: Iphone5s