package com.demo.test.Facotry;
/**
* (机能概要描述)
*
* <pre>
* [变更履历]
* 09.07.20.NICKLE NET 初版
* </pre>
*
* @author NICKLE)王
*/
interface Car1 {
public void run();
public void stop();
}
class Benz1 implements Car1 {
public void run() {
System.out.println("Benz is run......");
}
public void stop() {
System.out.println("Benz is stop......");
}
}
class Ford1 implements Car1 {
public void run() {
System.out.println("Ford is run.....");
}
public void stop() {
System.out.println("Ford is stop......");
}
}
class BigBus implements Car1 {
public void run() {
System.out.println("BigBus is run......");
}
public void stop() {
System.out.println("BigBus is stop......");
}
}
class MiniBus implements Car1 {
public void run() {
System.out.println("MiniBus is run......");
}
public void stop() {
System.out.println("MiniBus is stop......");
}
}
interface Factory1 {
}
class CarFactory1 implements Factory1 {
public Car1 getCar(String type) {
Car1 car = null;
try {
car = (Car1) Class.forName("com.demo.test.Facotry." + type)
.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return car;
}
}
class BusFactory1 implements Factory1 {
public Car1 getCar(String type) {
Car1 car = null;
try {
car = (Car1) Class.forName("com.demo.test.Facotry." + type)
.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return car;
}
}
public class FactoryDemo {
public static void main(String[] args) {
// CarFactory1 cf = new CarFactory1();
BusFactory1 bf = new BusFactory1();
// Car1 c = cf.getCar("Ford1");
Car1 c = bf.getCar("BigBus");
c.run();
c.stop();
}
}
什么时候应用工程模式: 当有族群,并且族群下有多个个体时。
特点:我们只需要告诉工程类,我们要什么样的目标类对象。工厂类便返回该类,降低耦合度。