首页 > 代码库 > 工厂模式思想代码实现
工厂模式思想代码实现
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;
}
}
工厂模式思想代码实现