`
angie_hawk7
  • 浏览: 46580 次
  • 性别: Icon_minigender_1
  • 来自: 乌托邦
社区版块
存档分类
最新评论

设计模式-1

 
阅读更多
1:策略模式
三个妙计,一个定囊,一个调用者。
private IStrategy straegy;
public Context(IStrategy strategy){
this.straegy = strategy;
}
public void operate(){
this.straegy.operate();
}


context = new Context(new BackDoor());
context.operate()

一个接口,多个实现类


2:代理模式
关键点:多态,同一个接口。
public interface KindWomen {
public void makeEyesWithMan(); //抛媚眼
public void happyWithMan(); //happy what? You know that!
}
public class PanJinLian implements KindWomen {
public void happyWithMan() {
System.out.println("潘金莲在和男人做那个.....");
}
public void makeEyesWithMan() {
System.out.println("潘金莲抛媚眼");
}
}

public class WangPo implements KindWomen {
private KindWomen kindWomen;
public WangPo(){ //默认的话,是潘金莲的代理
this.kindWomen = new PanJinLian();
}
//她可以是KindWomen的任何一个女人的代理,只要你是这一类型
public WangPo(KindWomen kindWomen){
this.kindWomen = kindWomen;
}
public void happyWithMan() {
this.kindWomen.happyWithMan(); //自己老了,干不了,可以让年轻的代替
}
public void makeEyesWithMan() {
this.kindWomen.makeEyesWithMan(); //王婆这么大年龄了,谁看她抛媚眼?!
}
}

public static void main(String[] args) {
//把王婆叫出来
WangPo wangPo = new WangPo();
//然后西门庆就说,我要和潘金莲happy,然后王婆就安排了西门庆丢筷子的那出戏:
wangPo.makeEyesWithMan(); //看到没,虽然表面上时王婆在做,实际上爽的是潘金莲
wangPo.happyWithMan(); }
}


3:单例模式
 public class SingletonPattern {
    	private static final SingletonPattern singletonPattern= new SingletonPattern();
    	//限制住不能直接产生一个实例
    	private SingletonPattern(){
    		
    	}
    	public synchronized static SingletonPattern getInstance(){
    	    return singletonPattern;
        }
    }

4:工厂模式:

public static Human createHuman(Class c){
    	Human human=null;
    	try{
    		human = (Human)Class.forName(c.getName()).newInstance();
    	}catch(InstantiationException e){
    		
    	}catch (IllegalAccessException e){
    		
    	}catch (ClassNotFoundException e) { 
    		
    	}
    }


重要应用:延迟初始化


5:抽象工厂模式:
一个接口,几个抽象类,然后是几个实现类
public interface Human {}

public abstract class AbstractYellowHuman implements Human {}
public class WhiteFemaleHuman extends AbstractWhiteHuman {}


6:门面模式:
方法的内部封装,暴漏给调用者的只是入口,过程不暴漏

7:适配器模式
一样的作用,不同的接口,不同的实现类。要完成接口的转化对接。
新定义一个接口,继承其中一个,实现另一个接口。

8:模板模式
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics