Simple FactoryFactory

巴扎黑
Release: 2016-12-20 15:29:23
Original
1321 people have browsed it

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停");
}
}
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!