Home  >  Article  >  Backend Development  >  Simple FactoryFactory

Simple FactoryFactory

巴扎黑
巴扎黑Original
2016-12-20 15:29:231378browse

package net.util;
/**
 * @项目名:spring2.5
 * @包名:net.util
 * @文件名:FactoryDemo.java
 * @日期:Jun 21, 2011 4:37:02 PM
 * @备注:工厂模式
 * @作者:apple
 */
public class FactoryDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Car c=Factory.getCarInstance("Banz");
if(c!=null){
c.run();
c.stop();
}
else{
System.out.println("制造不了");
}
}
}
class Factory{
public static Car getCarInstance(String type){
Car c=null;
try {
c=(Car)Class.forName("net.util."+type).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c;
}
}
interface  Car{
public void run();
public void stop();
}
class Banz implements Car{
public void run() {
// TODO Auto-generated method stub
System.out.println("Banz跑");
}
public void stop() {
// TODO Auto-generated method stub
System.out.println("Banz停");
}
}
class Ford implements Car{
public void run() {
// TODO Auto-generated method stub
System.out.println("Ford跑");
}
public void stop() {
// TODO Auto-generated method stub
System.out.println("Ford停");
}
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Simulate spring functionsNext article:Simulate spring functions