静态工厂模式
Animal
public abstract class Animal {
public abstract void call();
public static class Dog extends Animal {
@Override
public void call() {
System.out.println("Dog");
}
}
public static class Cat extends Animal {
@Override
public void call() {
System.out.println("Cat");
}
}
}
Factory
public class Factory {
public int Type_Dog=0;
public int Type_Cat=1;
public static Animal readAnimal(int Type){
switch (Type){
default:
return new Animal.Dog();
case 0:
return new Animal.Dog();
case 1:
return new Animal.Cat();
}
}
public static void main(String[] args){
Animal animal=Factory.readAnimal(1);
animal.call();
}
}
控制台输出:Cat
工厂方法模式
Factory
public interface Factory {
void onCall();
public class Dog implements Factory {
@Override
public void onCall() {
System.out.println("Dog");
}
}
public class Cat implements Factory {
@Override
public void onCall() {
System.out.println("Cat"); }
}
}
ChooseFactory
public interface ChooseFactory {
public Factory factory();
public class ChooseDog implements ChooseFactory{
@Override
public Factory factory() {
return new Factory.Dog();
}
}
public class ChooseCat implements ChooseFactory{
@Override
public Factory factory() {
return new Factory.Cat();
}
}
}
Animal
public class Animal {
public static void main(String[] args){
ChooseFactory DogFactory=new ChooseFactory.ChooseDog();
DogFactory.factory().onCall();
ChooseFactory CatFactory=new ChooseFactory.ChooseCat();
CatFactory.factory().onCall();
}
}
控制台输出:Dog
Cat
抽象工厂模式
Factory
public class Factory {
public interface Factory_Tiger{
void call();}
public interface Factory_Doger{
void call();}
public static class Dog implements Factory_Tiger {
@Override
public void call() {
System.out.println("Dog"); }}
public static class Cat implements Factory_Doger {
@Override
public void call() {
System.out.println("Cat");
}
}
}
ChooseFactory
public interface ChooseFactory {
public Factory.Dog build_dog();
public Factory.Cat build_Tiger();
public static class BuildFactory implements ChooseFactory {
@Override
public Factory.Dog build_dog() {
return new Factory.Dog();
}
@Override
public Factory.Cat build_Tiger() {
return new Factory.Cat();
}
}
}
Animal
public class Animal {
public static void main(String[] args){
ChooseFactory factory=new ChooseFactory.BuildFactory();
factory.build_dog().call();
factory.build_Tiger().call();
}
}
控制台输出:Dog
Cat
Effective+Java作者joshua bloch(Java 集合框架创办人、谷歌首席java架构师)建议,考虑用静态工厂方法来代替多个构造函数。
第一个优点,有名称,有时候一个类的构造器不止一个,名称往往相同,参数不同,很难理解他们有什么不同的含义,如果使用静态工厂方法,就一目了然知道设计者想表达的意图。
第二个优点,不用重复创建一个对象。
第三个优点,可以返回类型的任何子类型.举个例子,
List list = Collections.synchronizedList(new ArrayList())
这个例子就说明了可以返回原返回类型的任何子类型的对象。
缺点:1.公有的静态方法所返回的非公有类不能被实例化,也就是说Collections.synchronizedList返回的SynchronizedList不能被实例化。
2.查找API比较麻烦,它们不像普通的类有构造器在API中标识出来,在文档中要详细说明实例化一个类,非常困难。