简单工厂模式又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例
优点:
客户端不需要在负责对象的创建,从而明确了各个类的职责
缺点:
这个静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期的维护
简单代码体现
//测试类
package Cn.Itcast_shejimoshi;
public class AnimalDemo {
public static void main(String[] args) {
Dog d=AnimalFactory.CreateDog();
Cat c=AnimalFactory.CreateCat();
d.eat();
c.eat();
}
}
public class AnimalDemo {
public static void main(String[] args) {
Dog d=AnimalFactory.CreateDog();
Cat c=AnimalFactory.CreateCat();
d.eat();
c.eat();
}
}
//工厂类
package Cn.Itcast_shejimoshi;
public class AnimalFactory {
private AnimalFactory() {
}
public static Cat CreateCat(){
return new Cat();
}
public static Dog CreateDog() {
return new Dog();
}
}
public class AnimalFactory {
private AnimalFactory() {
}
public static Cat CreateCat(){
return new Cat();
}
public static Dog CreateDog() {
return new Dog();
}
}
//抽象动物类
package Cn.Itcast_shejimoshi;
public abstract class Animal {
public abstract void eat();
}
public abstract class Animal {
public abstract void eat();
}
//具体实现类
package Cn.Itcast_shejimoshi;
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
package Cn.Itcast_shejimoshi;
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}