建造者模式
这个例子的优雅之处在于初始化可以针对不同的需求择要构造。哈哈。
show the code from 《effetive java》 the 2 item!
package Builder;
public class NutritionFacts {
private final int servingSize;
private final int servings;
private final int calories;
private final int fat;
private final int sodium;
private final int carbohydrate;
public static class Builder {
private final int servingSize;
private final int servings;
private int calories = 0;
private int fat = 0;
private int sodium = 0;
private int carbohydrate = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
public Builder calories(int val) {
this.calories = val;
return this;
}
public Builder fat(int val) {
this.fat = val;
return this;
}
public Builder sodium(int val) {
this.sodium = val;
return this;
}
public Builder carbohydrate(int val) {
this.carbohydrate = val;
return this;
}
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
servingSize = builder.servingSize;
servings = builder.servings;
calories = builder.calories;
fat = builder.fat;
carbohydrate = builder.carbohydrate;
sodium = builder.sodium;
}
public static void main(String[] args) {
//initial the field which you like!
//for exsample one
NutritionFacts nutrition1 = new Builder(10, 12).calories(3).sodium(4)
.build();
//exsample second
NutritionFacts nutrition2 = new Builder(23,45).fat(100).build();
}
}
装饰器模式(decorator)
这个或者说是组合模式,是为了消除继承破坏封装性(因为如果没有is a的逻辑,尽量不要用继承,不然逻辑会越来越混乱)。
the code from effective java the 17 item but codes is mine imulate.
package Decorator;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
public class MySet<T> extends OurSet<T> {
@Override
public int size() {
// do sth
return super.size();
}
public MySet(Set<T> s) {
super(s);
}
// do sth
}
class OurSet<T> implements Set<T> {
public OurSet(Set<T> s) {
super();
this.s = s;
}
private final Set<T> s;
@Override
public int size() {
return s.size();
}
@Override
public boolean isEmpty() {
return s.isEmpty();
}
@Override
public boolean contains(Object o) {
return s.contains(o);
}
@Override
public Iterator iterator() {
return s.iterator();
}
@Override
public Object[] toArray() {
return s.toArray();
}
@Override
public Object[] toArray(Object[] a) {
return s.toArray(a);
}
@Override
public boolean add(Object e) {
return s.add((T) e);
}
@Override
public boolean remove(Object o) {
return s.remove(o);
}
@Override
public boolean containsAll(Collection c) {
return s.containsAll(c);
}
@Override
public boolean addAll(Collection c) {
return s.addAll(c);
}
@Override
public boolean retainAll(Collection c) {
return false;
}
@Override
public boolean removeAll(Collection c) {
return s.removeAll(c);
}
@Override
public void clear() {
s.clear();
}
}