观察者
- 给被观察的类里面注入观察者对象(接口的实现类)
- 被观察的类会调用观察者的接口方法
适配器
- 适配器实现了德国的接口,会调用德国的方法
- 适配器初始化时给它注入新的接口,调用德国方法里面调用新接口的方法实现
策略模式
public abstract class Duck {
private Flyable flyable;//接口
public void setFlyable(Flyable flyable) {
this.flyable = flyable;
}
public void fly() {
flyable.fly();
}
public Duck() {
}
}
单例模式
public class Single {
private Single() {
} // 私有化构造函数
private static Single s = new Single();// 创建私有并静态的本类对象
public static Single getInstance() {// 公共并静态的方法,返回该对象
return s;
}
}
- 懒汉式
public class Single {
private Single() {
};
private static Single instance = null;
public static Single getInstance() {
if (instance == null) {
//只有第一次创建的时候才会判断同步锁,之后就不判断了
synchronized (Single.class) {
if (instance == null) {
instance = new Single();
}
}
}
return instance;
}
}
静态工厂方法
public class FragmentFactory {
private static Map<Integer, BaseFragment> mFragments = new HashMap<Integer, BaseFragment>();
public static BaseFragment createFragment(int position) {
BaseFragment fragment = null;
fragment = mFragments.get(position); //在集合中取出来Fragment
if (fragment == null) { //如果在集合中没有取出来 需要重新创建
if (position == 0) {
fragment = new HomeFragment();
} else if (position == 1) {
fragment = new AppFragment();
} else if (position == 2) {
fragment = new GameFragment();
} else if (position == 3) {
fragment = new SubjectFragment();
} else if (position == 4) {
fragment = new CategoryFragment();
} else if (position == 5) {
fragment = new TopFragment();
}
if (fragment != null) {
mFragments.put(position, fragment);// 把创建好的Fragment存放到集合中缓存起来
}
}
return fragment;
}
}
装饰设计模式(com.mysql.jdbc.Connection被包装类 close())
a、编写包装类,实现与被包装类相同的接口(使他们有共同的行为)
b、定义一个变量,引用被包装类的实例(最好做到与具体驱动无关)
c、定义包装类的构造方法,传入被包装类的实例(注入:DI)
d、对于需要改写的方法,编写自己的代码
e、对于不需要改写的方法,调用被包装类的对应方法