工厂方法模式

来源:互联网 发布:淘宝怎么下架商品 编辑:程序博客网 时间:2024/05/22 00:24

1.工厂方法模式


1.1普通工厂模式:就是建立了一个工厂类,对实现了同一接口的一些类进行实例的创建.以便将创建对象的具体过程屏蔽起来,达到提高灵活性。后来自己在写的过程中确实能体现到这一优点。
/** *   First ,create the interface of both */public interface Sender {public void send();}

创建实现类

/** * create the implements class */    public class MailSender implements Sender {        public void send(){    System.out.println("This is a mailsender");    }}

创建实现类

/** * create the implement class */public class SmsSender implements Sender {public void send() {    System.out.println("This is a sms sender");    }}

创建工厂类

/** * Created by admin  */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 sendFactory = new SendFactory();    Sender sender =  sendFactory.produce("sms");    sender.send();    }}

1.2多个工厂方法模式:是对普通工厂方法模式的改进,在普通工厂方法模式中,如果传递的字符串出错,则不能正确创建对象,而多个工厂方法模式是提供多个工厂方法,分别创建对象。

/** * 首先创建两个的共同接口 */public interface Sender {    public void send();}

创建实现类

/** * create the implements class */    public class MailSender implements Sender {        public void send(){    System.out.println("This is a mailsender");    }}

创建实现类

/** * create the implement class */public class SmsSender implements Sender {public void send() {    System.out.println("This is a sms sender");    }}

改动下SendFactory类

public class SendFactory {public Sender1 produceMail(){    return new MailSender1();    }public Sender1 produceSms(){    return new SmsSender1();    }}

测试

public class FactoryTest {public static void main(String[] args) {    SendFactory1 factory = new SendFactory1();    Sender1 sender = factory.produceMail();    sender.send();    }}

1.3静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。

代码就不写了,反正这都是根据网上的例子来手敲一遍的

总结
(1)简单工厂模式是由一个具体的类去创建其他类的实例,父类是相同的,父类是具体的。
(2)工厂方法模式是有一个抽象的父类定义公共接口,子类负责生成具体的对象,这样做的目的是将类的实例化操作延迟到子类中完成。