首页 > 学院 > 开发设计 > 正文

设计模式-工厂模式(简单工厂模式和方法工厂模式)

2019-11-06 07:18:35
字体:
来源:转载
供稿:网友

一、简单工厂模式

简单工厂模式概述•又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例优点•客户端不需要在负责对象的创建,从而明确了各个类的职责缺点•这个静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期的维护代码://动物类

public abstract class Animal {    public abstract void eat();}

//猫类

public class Cat extends Animal {    @Override    public void eat() {        System.out.PRintln("猫吃鱼");    }}

//狗类

public class Dog extends Animal {    @Override    public void eat() {        System.out.println("狗吃肉");    }}

//动物工厂

public class AnimalFactory {    private AnimalFactory() {    }    public static Animal createAnimal(String type) {        if ("dog".equals(type)) {            return new Dog();        } else if ("cat".equals(type)) {            return new Cat();        } else {            return null;        }    }}

//测试类

public class AnimalDemo {    public static void main(String[] args) {        // 具体类调用        Dog d = new Dog();        d.eat();        Cat c = new Cat();        c.eat();        System.out.println("------------");        Animal a = AnimalFactory.createAnimal("dog");        a.eat();        a = AnimalFactory.createAnimal("cat");        a.eat();        // NullPointerException        a = AnimalFactory.createAnimal("pig");        if (a != null) {            a.eat();        } else {            System.out.println("对不起,暂时不提供这种动物");        }    }}

二、工厂方法模式

工厂方法模式概述•工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。优点•客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性缺点•需要额外的编写代码,增加了工作量//动物类

public abstract class Animal {    public abstract void eat();}

//工厂接口

public interface Factory {    public abstract Animal createAnimal();}

//猫类

public class Cat extends Animal {    @Override    public void eat() {        System.out.println("猫吃鱼");    }}

//狗类

public class Dog extends Animal {    @Override    public void eat() {        System.out.println("狗吃肉");    }}

//猫工厂类

public class Cat extends Animal {    @Override    public void eat() {        System.out.println("猫吃鱼");    }}

//狗工厂类

public class DogFactory implements Factory {    @Override    public Animal createAnimal() {        return new Dog();    }}

//测试类

public class AnimalDemo {    public static void main(String[] args) {               Factory f = new DogFactory();        Animal a = f.createAnimal();        a.eat();        System.out.println("-------");                        f = new CatFactory();        a = f.createAnimal();        a.eat();    }}


上一篇:Server.MapPath()

下一篇:命名空间

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表