设计模式(一)

一、工厂模式

二、抽象工厂模式

三、单例模式

四、建造者模式

一、工厂模式:隐藏对象创建逻辑,并使用共同接口指向新创建的对象

例如实现接口Shape,有Circle,Rectangle等。各自实现Shape里的draw方法。把new出来的各种”Shape”放到Shape里,调用shape.draw()

1
shapeFactory.getShape("CIRCLE").draw();

二、抽象工厂模式:把工厂也当成一个需要创建的对象

1
2
AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
colorFactory.getColor("RED").fill();

三、单例模式:分为懒汉式(用到才创建,省内存,需要考虑线程安全)、饿汉式(类加载就创建,非lazy loading)

懒汉式,线程安全

1
2
3
4
5
6
7
8
9
10
public class Singleton { 
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

饿汉式(推荐)

1
2
3
4
5
6
7
public class Singleton { 
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}

静态内部类,资源利用率高,第一次加载不够快

1
2
3
4
5
6
7
8
9
public class Singleton {
private Singleton(){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}

四、建造者模式:对于内部复杂的结构,单独设置一个类来完成构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MealBuilder {
public Meal prepareVegMeal (){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
}
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = mealBuilder.prepareVegMeal();
System.out.println("Veg Meal");
vegMeal.showItems();
System.out.println("Total Cost: " +vegMeal.getCost());
}
参考资料

http://www.cnblogs.com/damsoft/p/6105122.html