1.簡(jiǎn)單工廠模式(這里只是簡(jiǎn)單舉例 代碼不規(guī)范處還需諒解)
原則: 提供創(chuàng)建對(duì)象的功能慈参,不需要關(guān)心具體的實(shí)現(xiàn)
//創(chuàng)建一個(gè)汽車的抽象類
public abstract class Car {
protected String name;
protected final static String CARSTYLE = "汽車";
public abstract String drive();
public String getName() {
return this.name;
}
}
//子類實(shí)現(xiàn)父類
public class BackCar extends Car {
@Override
public String drive() {
return name+Car.CARSTYLE;
}
}
//創(chuàng)建一個(gè)工廠類負(fù)責(zé)具體的對(duì)象的創(chuàng)建
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 "藍(lán)色":
car=new BuleCar();
break;
}
return car;
}
}
//在客戶的調(diào)用(根據(jù)傳入的參數(shù)類型不同 而構(gòu)建不同的對(duì)象)
Car car = CarFactory.newCar(RED);
tv_text.setText(car.drive());
由上可以看出 對(duì)對(duì)象的具體實(shí)現(xiàn)實(shí)現(xiàn)的隱藏
弊端:
1.不符合開閉原則 如果有新的對(duì)象生成 需要改寫工廠類
2.不符合單一原則 工廠類是根據(jù)類型來判斷創(chuàng)建哪種汽車的
二. 升級(jí)簡(jiǎn)單工廠方法
//創(chuàng)建一個(gè)注解類
@Target(ElementType.TYPE)//用于描述類呛牲、接口(包括注解類型) 或enum聲明
@Retention(RetentionPolicy.RUNTIME)//即運(yùn)行時(shí)保留
@Documented //用于描述其它類型的annotation應(yīng)該被作為被標(biāo)注的程序成員的公共API
@Inherited //修飾的annotation類型被用于一個(gè)class 則這個(gè)Annotation將被用于該class的子類。
public @interface CarColor {
String color() default "";
}
//使用注解
@CarColor(color="BACK")
public class BackCar extends Car {
@Override
public String drive() {
return name+Car.CARSTYLE;
}
}
//創(chuàng)建工廠方法 根據(jù)對(duì)象類型來構(gòu)建對(duì)應(yīng)的對(duì)象
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;
}
}
//客戶頓調(diào)用(傳入對(duì)應(yīng)的對(duì)象類型來構(gòu)建對(duì)應(yīng)的對(duì)象 其中應(yīng)用到了反射和注解)
car= CarFactory2.newCar(BuleCar.class);
tv_text.setText(car.drive());