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

—-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("程序错误");
    }


}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值