反射结合工厂设计模式的使用

来源:互联网 发布:华为海洋网络 面试 编辑:程序博客网 时间:2024/05/21 08:46

package Hg

//反射结合工厂设计模式的使用

pbulic class FactoryDEMO

public static void void main(String[] args){

Fruit Fruit = Factory.getFruit("Hg.Apple");

fruit.eat();

}

}

//接口

intterface Fruit{

void eat();

}

//实现类

class Apple implements Fruit{

@Override

public void eat(){

System.out.println("吃苹果");

}

}

class pinappale implements Fruit{

@Override

public void eat(){

System.out.println("吃菠萝")

}

}

//工厂类

class Factory{

public static Fruit getFruit(String className){

Fruit f = null;

try{

Class<?> cls = Class.forhome(className);

f = (Fruit)cls.newinstance();

}catch(ClassNotFoundException e){

//TODO Auto-generated catch block

e.printStackTrace();

}

return;

}

}

0 0
原创粉丝点击