您的位置:首页 > 其它

类对象工厂设计模式(Factory Pattern)

2013-05-13 22:54 567 查看
本文朋友在深圳逛街的时候突然想到的...这段时间就有想写几篇关于类对象的笔记,所以回家到之后就奋笔疾书的写出来发布了

提供了比工厂模式更高一级的接口级,用于返回若个工厂之一。这个模式是属于创立模式之一。有几点值得注意:

对象的创立充分重用重要的代码。

对象的创立需要访问某个信息或者资源时,这对象不应该包含在组合类中。

一般对象生命周期管理必须集中化,确保应用程序中行为的一致性。

分析一个例子,如下:

定义一个枚举类型的CarType类,列出车的类型。

public enum CarType {
SMALL, SEDAN, LUXURY
}


抽象Car类,全部的子类扩展Car这个类实现自己的特有功能。

public abstract class Car {

private CarType model = null;

public Car(CarType model) {
this.model = model;
arrangeParts();
}

private void arrangeParts() {
// Do one time processing here
}

// Do subclass level processing in this method
protected abstract void construct();

public CarType getModel() {
return model;
}

public void setModel(CarType model) {
this.model = model;
}
}


分别定义SmallCar、Sedan和Luxury类。

public class SmallCar extends Car{

SmallCar() {
super(CarType.SMALL);
construct();
}

@Override
protected void construct() {
System.out.println("Building small car");
// add accessories
}
}


public class SedanCar extends Car {
SedanCar() {
super(CarType.SEDAN);
construct();
}

@Override
protected void construct() {
System.out.println("Building sedan car");
// add accessories
}
}


public class LuxuryCar extends Car {
LuxuryCar() {
super(CarType.LUXURY);
construct();
}

@Override
protected void construct() {
System.out.println("Building luxury car");
// add accessories
}
}

定义FactoryCar工厂类,事实详细的调用。

public class CarFactory {
public static Car buildCar(CarType model) {
Car car = null;
switch (model) {
case SMALL:
car = new SmallCar();
break;

case SEDAN:
car = new SedanCar();
break;

case LUXURY:
car = new LuxuryCar();
break;

default:
// throw some exception
break;
}
return car;
}
}


测试工厂类,单元测试如下:

每日一道理

宽容,是一种坦荡,可以无私无畏,无拘无束,无尘无染。宽容,是一种豁达,是比海洋和天空更为博大的胸襟,是宽广和宽厚的叠加,延续和升华。宽容有度,宽容无价,宽以待人,这是人生处世的基本法则。

public class CarFactoryTest {

@SuppressWarnings("deprecation")
@Test
public void testCarFactory() {
Assert.assertEquals(true, CarFactory.buildCar(CarType.SMALL) instanceof Car) ;
Assert.assertEquals(true, CarFactory.buildCar(CarType.SEDAN) instanceof Car) ;
Assert.assertEquals(true, CarFactory.buildCar(CarType.LUXURY) instanceof Car) ;
}
}


输出结果如下:

Building small car
Building sedan car
Building luxury car


工厂模式的使用场所:

1.创立相干的家族或是依赖对象,比如Kit.
2. 提供一个产品类库,显现接口,但是不包括实现。
3. 修要从超类哪里断绝详细的实现类.
4. 系统需要独立出系统的产品如何创立、组合和呈现。
如果你想做一深刻的研究,可以查阅Java API代码.

java.sql.DriverManager#getConnection()

java.net.URL#openConnection()

java.lang.Class#newInstance()

java.lang.Class#forName()

文章结束给大家分享下程序员的一些笑话语录:

3G普不普及现在已经不是看终端了,而是看应用,有好的,便宜实用的应用,花1000多买个能用的智能手机应该不是什么难事。反过来说,你200元拿一个智能手机,没有好的应用,看个电影要几十元,也是没人用3G。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: