工厂模式


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();
}
}



什么时候应用工程模式: 当有族群,并且族群下有多个个体时。
特点:我们只需要告诉工程类,我们要什么样的目标类对象。工厂类便返回该类,降低耦合度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值