工厂模式

简单工厂模式:又叫静态方法工厂模式。
优点:客户端不需要在负责对象的创建,明确了各个类的职责。
缺点:这个静态工厂负责所有对象的创建,有新对象增加,或者某些对象的创建方式不同,就需要不断地修改工厂类,不利于后期维护。

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) {
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 class Cat extends Animal {

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

}
public class Dog extends Animal {

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

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

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

public interface Factory {
    public abstract Animal createAnimal();
}
public class DogFactory implements Factory {

    @Override
    public Animal createAnimal() {
        return new Dog();
    }

}
public class Dog extends Animal {

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

}
public class CatFactory implements Factory {

    @Override
    public Animal createAnimal() {
        return new Cat();
    }

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

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

}
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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值