无聊,复习一下工厂模式
一个抽象父类Animal,子类有Duck,Pig,Bird,继承Animal,一个工厂类FactoryModel,负责初始化Animal对应的子类
Animal类:
public abstract class Animal {
public Animal(){
System.out.println("eat behavior...");
}
public void shape(){
}
public void color(){}
public void category(String type){
switch (type){
case "0":{
System.out.println("飞禽");
break;
}
case "1":{
System.out.println("走兽");
break;
}
case "2":{
System.out.println("妖魔");
break;
}
case "3":{
System.out.println("鬼怪");
break;
}
case "4":{
System.out.println("水产");
break;
}
}
}
}
bird类
public class Bird extends Animal {
@Override
public void color() {
System.out.println("大红鸟");
}
@Override
public void shape() {
System.out.println("锥子鸟形状");
}
}
duck类
public class Duck extends Animal{
@Override
public void color() {
System.out.println("灰色的鸭子gray");
}
@Override
public void shape() {
System.out.println("火箭型状的鸭子");
}
}
pig类就不写了,大同小异
下面是工厂类,负责实例化
public class FactoryModel {
private Animal animal;
public Animal initAnimal(String obj){
switch (obj){
case "duck":{
this.animal=new Duck();
break;
}
case "pig":{
this.animal=new Pig();
break;
}
case "bird":{
this.animal=new Bird();
break;
}
}
return animal;
}
}
测试启动类
public class MainClass {
public static void main(String[] args) {
FactoryModel factoryModel = new FactoryModel();
Animal duck = factoryModel.initAnimal("duck");
Animal pig = factoryModel.initAnimal("pig");
Animal bird = factoryModel.initAnimal("bird");
duck.color();
duck.shape();
duck.category("4");
pig.shape();
pig.color();
pig.category("1");
bird.shape();
bird.color();
}
}