简单工厂模式

2017-02-21  本文已影响33人  明朗__

1.简单工厂模式(这里只是简单举例 代码不规范处还需谅解)

原则: 提供创建对象的功能,不需要关心具体的实现

//创建一个汽车的抽象类
public abstract class Car {

    protected String name;

    protected final static String CARSTYLE = "汽车";

    public abstract String drive();

    public String getName() {
        return this.name;
    }
}
//子类实现父类
public class BackCar extends Car {
    @Override
    public String drive() {
        return name+Car.CARSTYLE;
    }
}
//创建一个工厂类负责具体的对象的创建
public class CarFactory {
    public static Car newCar(String color){
        Car car=null;
        switch (color){
            case "黑色":
                car=new BackCar();
                break;
            case "红色":
                car=new RedCar();
                break;
            case "蓝色":
                car=new BuleCar();
                break;
        }
        return car;
    }
}
//在客户的调用(根据传入的参数类型不同 而构建不同的对象)
 Car car = CarFactory.newCar(RED);
 tv_text.setText(car.drive());

由上可以看出 对对象的具体实现实现的隐藏

弊端:
1.不符合开闭原则 如果有新的对象生成 需要改写工厂类
2.不符合单一原则 工厂类是根据类型来判断创建哪种汽车的

二. 升级简单工厂方法

//创建一个注解类
@Target(ElementType.TYPE)//用于描述类、接口(包括注解类型) 或enum声明
@Retention(RetentionPolicy.RUNTIME)//即运行时保留
@Documented //用于描述其它类型的annotation应该被作为被标注的程序成员的公共API
@Inherited //修饰的annotation类型被用于一个class 则这个Annotation将被用于该class的子类。
public @interface CarColor {
    String color() default "";
}
//使用注解
@CarColor(color="BACK")
public class BackCar extends Car {
    @Override
    public String drive() {
        return name+Car.CARSTYLE;
    }
}
//创建工厂方法 根据对象类型来构建对应的对象
public class CarFactory2 {

    public static <T extends Car> T newCar(Class<T> c) {
        Car car = null;
        String identifier = null;
        try {
            Class componentClass = Class.forName(c.getName());
            if (componentClass.isAnnotationPresent(CarColor.class)) {//制定类型的注释存在该元素之上
                CarColor component = (CarColor) componentClass.getAnnotation(CarColor.class);
                identifier = component.color();
                System.out.println(String.format("颜色:' %s '", identifier));
            } else {
                System.out.println("com.jasongj.UpperCaseComponent is not annotated by"
                        + " com.jasongj.annotation.Component");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        try {
            car = (Car) Class.forName(c.getName()).newInstance();
            car.name = identifier;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) car;
    }
}
//客户顿调用(传入对应的对象类型来构建对应的对象 其中应用到了反射和注解)
 car= CarFactory2.newCar(BuleCar.class);
 tv_text.setText(car.drive());
上一篇下一篇

猜你喜欢

热点阅读