简单工厂模式

工厂方法模式的对简单工厂模式进行了抽象。有一个抽象的Factory类(可以是抽象类和接口),这个类将不在负责具体的产品生产,而是只制定一些规范,将实际创建工作推迟到子类去完成

在这个模式中,工厂类和产品类往往依次对应。即一个抽象工厂对应一个抽象产品,一个具体工厂对应一个具体产品,这个具体的工厂就负责生产对应的产品

简单工厂模式为什么不属于23个设计模式中一个,因为他不符合开闭原则。

代码:
/**
 * 我们举一个发送邮件和短信的例子
 * @author Liufei
 * @date 2020/4/10 12:01 下午
 */
public interface Sender {
    void send();
}
/**
 * @author Liufei
 * @date 2020/4/10 12:02 下午
 */
public class MailSender implements Sender {
    @Override
    public void send() {
        System.out.println("this is mailSender");
    }
}
/**
 * @author Liufei
 * @date 2020/4/10 12:03 下午
 */
public class SmsSender implements Sender {
    @Override
    public void send() {
        System.out.println("this is mailSender");
    }
}
/**
 * @author Liufei
 * @date 2020/4/10 12:03 下午
 */
public class SenderFactory {
    public Sender product(String type) {
        if ("mail".equals(type)) {
            return new MailSender();
        } else if ("sms".equals(type)) {
            return new SmsSender();
        } else {
            System.out.println("请输入正确的类型!");
            return null;
        }
    }
}
/**
 * @author Liufei
 * @date 2020/4/10 2:01 下午
 */
public class FactoryTest {
    public static void main(String[] args) {
        SenderFactory senderFactory = new SenderFactory();
        Sender mail = senderFactory.product("mail");
        mail.send();
    }
}




posted @ 2021-08-04 00:14  刘翊扬  阅读(39)  评论(0编辑  收藏  举报