工厂设计模式
抽象工厂,用于规定具体工厂需具备的功能(方法)
GirlFriend.java
public abstract class GirlFriend {//抽象工厂,规定了girlfriend需要具备的方法,也用于上转型调用
public abstract void speak();
}
三个具体工厂
WangGirl.java
public class WangGirl extends GirlFriend {//"生产"WangGirl的工厂
public void speak() {//抽象方法的实现
System.out.println("My name is 王**");
}
}
LiuGirl.java
public class LiuGirl extends GirlFriend {//"生产"LiuGirl的工厂
public void speak() {
System.out.println("My name is 刘*");
}
}
GaoGirl.java
public class GaoGirl extends GirlFriend {//"生产"GaoGirl的工厂
public void speak() {
System.out.println("My name is 高*");
}
}
简单工厂类SimpleFactory,java
public class SimpleFactory {//简单工厂类,根据传入的参数返回对应的类实例
final static int TYPE_wang=1;
final static int TYPE_liu=2;
final static int TYPE_gao=3;
public static GirlFriend createGirlFriend(int type) {
switch(type) {
case TYPE_wang:
return new WangGirl();
case TYPE_liu:
return new LiuGirl();
default:
return new GaoGirl();
}
}
}
包含main方法的测试类TestSimpleFactory.java
public class TestSimpleFactory {
public static void main(String[] args) {
GirlFriend gf=SimpleFactory.createGirlFriend(SimpleFactory.TYPE_wang);//传入1,返回new WangGirl()
gf.speak();//对象的丄转型
gf=SimpleFactory.createGirlFriend(SimpleFactory.TYPE_gao);//传入3,返回new GaoGirl()
gf.speak();//对象的丄转型
}
}