首先定义一个接口:
package a.build_type;
public abstract class Animal {
public abstract void eat();
}
接口的实现:
package a.build_type;
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
package a.build_type;
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃肉");
}
}
简单工厂:
package b.build_type_factory;
import a.build_type.Animal;
import a.build_type.Cat;
import a.build_type.Dog;
/**
* 简单工厂模式:
* 简单工厂模式又叫静态工厂方法模式,它定义一个
* 具体的工厂类负责创建一些类的实例。
*
* 优点:
* 客户不需要在负责对象的创建,从而明确了各个类
* 的职责。
* 缺点:
* 这个静态工厂负责所有对象的创建,如果有新的对象
* 增加,或者某些对象的创建方式不同,就需要不断的
* 修改工厂类,不利于后期的维护。
*
* @author 半步疯子
*
*/
public class AnimalFactory01 {
// 私有化构造方法,提供静态调用
private AnimalFactory01() {}
/*
public static Dog createDog() {
return new Dog();
}
public static Cat createCat() {
return new Cat();
}
*/
public static Animal createAnimal(String type) {
if("dog".equals(type)) {
return new Dog();
} else if("cat".equals(type)) {
return new Cat();
} else {
return null;
}
}
}
测试调用:
package b.build_type_factory;
import a.build_type.Animal;
import a.build_type.Cat;
import a.build_type.Dog;
public class AnimalTest01 {
public static void main(String[] args) {
// 具体调用
Dog d = new Dog();
d.eat();
Cat c = new Cat();
c.eat();
System.out.println("------------");
/*
* 但是很多时候,造对象是一件很复杂的事情
* 这里简单,因为我们的猫和狗都是调用的无
* 参构造进行构造的。
*/
// 有了工厂之后:
/*
Dog dog = AnimalFactory01.createDog();
Cat cat = AnimalFactory01.createCat();
dog.eat();
cat.eat();
*/
// 工厂改进后:
Animal a = AnimalFactory01.createAnimal("dog");
if(a != null)
a.eat();
a = AnimalFactory01.createAnimal("cat");
if(a != null)
a.eat();
}
}