* 简单工厂设计模式(编写的类是:花类,草类,树类,父类是植物类)

—-classOne
package firstExam.first;
public abstract class Plant {
public abstract void function();

}
—-classTwo
package firstExam.first;

public class Flower extends Plant {

@Override
public void function(){
    System.out.println("我是鲜花");

}

}
—-classThree
package firstExam.first;

public class Grass extends Plant{

@Override
public void function() {
    System.out.println("我是小草");

}

}
—-classFour
package firstExam.first;

public class Tree extends Plant {

@Override
public void function() {
    System.out.println("我是大树");

}

}
—-classFive
package firstExam.first;

public class Commons {

public final static int TREE_TYPE=1;
public final static int FLOWER_TYPE=2;
public final static int GRASS_TYPE=3;

}
—-classSix
package firstExam.first;

public class PlantFactory {

public static Plant createPlant(int type){
    switch(type){
    case 1:
        return new Tree();
    case 2:
        return new Flower();
    case 3:
        return new Grass();
    default:
        break;
    }
    return null;
}

}
—-classSeven
package firstExam.first;
/**
* 简单工厂设计模式(编写的类是:花类,草类,树类,父类是植物类)
*/
public class Test {

public static void main(String[] args) {
    PlantFactory pFactory=new PlantFactory();
    Plant myPlant=pFactory.createPlant(Commons.TREE_TYPE);

    if(myPlant instanceof Flower){
        Flower flower=(Flower)myPlant;
        flower.function();
    }else if(myPlant instanceof Tree){
        Tree tree=(Tree)myPlant;
        tree.function();
    }else if(myPlant instanceof Grass){
        Grass grass=(Grass)myPlant;
        grass.function();
    }else{
        System.out.println("程序错误");
    }


}

}

猜你喜欢

转载自blog.csdn.net/qq_38986609/article/details/78488511