标签:app 工厂 get factory oid 代码实现 gen try void
package com.tzh.spring.factory;
/**
*买手机
* 工厂设计模式
* @author TZH
*
*/
//定义一个接口
interface Company{
//void getPhone()也可以;
abstract void getPhone();
}
class SamsungCompany implements Company{
public void getPhone(){
System.out.println("Samsung getPhone");
}
}
class AppleCompany implements Company{
public void getPhone(){
System.out.println("Apple getPhone");
}
}
class HuaweiCompany implements Company{
public void getPhone(){
System.out.println("Huawei getPhone");
}
}
public class Factorytest {
public static void main(String[] args) {
// Company company = get("com.tzh.spring.factory.SamsungCompany");
// if(company!=null){
// company.getPhone();
// }
Company company = get(SamsungCompany.class);
if(company!=null){
company.getPhone();
}
}
// public static Company get(String class1){
// try {
// return (Company) Class.forName(class1).newInstance();
// } catch (InstantiationException | IllegalAccessException
// | ClassNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return null;
// }
//用到反射和接口结合
public static Company get(Class class1){
try {
return (Company) class1.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
标签:app 工厂 get factory oid 代码实现 gen try void
原文地址:http://www.cnblogs.com/t658/p/6714649.html