主要内容:
1.工厂方法模式
2.多个工厂方法模式
3.静态方法模式
一.工厂方法模式
public abstract class Animal {
public abstract void eat();
}
public class Cat extends Animal {
@Override
public void eat() {
}
}
<pre name="code" class="java">public class Dog extends Animal {@Overridepublic void eat() {}}
<pre name="code" class="java">package factory;
public class AnimalFactory1 {
public Animal createAnimal(String animal) {
if ("dog".equals(animal)) {
return new Dog();
}
if ("cat".equals(animal)) {
return new Cat();
}
return null;
}
}
二.多个工厂方法模式
public class AnimalFactory2 {
public Animal createDog() {
return new Dog();
}
public Animal createCat() {
return new Cat();
}
}
三.静态方法模式
public class AnimalFactory3 {
public static Animal createDog() {
return new Dog();
}
public static Animal createCat() {
return new Cat();
}
}
四.测试
@Test
public void test1() {
AnimalFactory1 factory = new AnimalFactory1();
Animal a1 = factory.createAnimal("cat");
Animal a2 = factory.createAnimal("dog");
a1.eat();
a2.eat();
}
@Test
public void test2() {
AnimalFactory2 factory = new AnimalFactory2();
Animal a1 = factory.createCat();
Animal a2 = factory.createDog();
a1.eat();
a2.eat();
}
@Test
public void test3() {
Animal a1 = AnimalFactory3.createCat();
Animal a2 = AnimalFactory3.createDog();
a1.eat();
a2.eat();
}
效果都一样,代码不一样,这样看来是第三种比较好了.