JAVA SE之工厂模式(李兴华第一行代码)

来源:互联网 发布:日语翻译 知乎 编辑:程序博客网 时间:2024/05/22 13:44
interface Fruit{// 定义一个水果接口public void eat() ;// 吃水果}class Apple implements Fruit{public void eat(){System.out.println("** 吃苹果。") ;}};class Orange implements Fruit{public void eat(){System.out.println("** 吃橘子。") ;}};class Factory{// 定义工厂类public static Fruit getInstance(String className){Fruit f = null ;if("apple".equals(className)){// 判断是否要的是苹果的子类f = new Apple() ;}if("orange".equals(className)){// 判断是否要的是橘子的子类f = new Orange() ;}return f ;}};public class InterfaceCaseDemo04{public static void main(String args[]){Fruit f = Factory.getInstance("Apple") ;// 实例化接口f.eat() ;}};

阅读全文
0 0
原创粉丝点击