1、策略模式
理解:就是通过传不同的参数,调用不同的对象
代码实操
public interface IStrategy { void operate(); } public class BackDoor implements IStrategy { public void operate() { System.out.println("找乔国老帮忙,让吴国太给孙权施加压力"); } } public class GivenGreenLight implements IStrategy { public void operate() { System.out.println("求吴国太开个绿灯,放行!"); } } public class Context { private IStrategy iStrategy; public Context(IStrategy iStrategy) { this.iStrategy = iStrategy; } public void operate(){ this.iStrategy.operate(); } } public class Zhaoyun { public static void main(String[] args) { Context 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 ProxyClass { private KindWomen kindWomen; public ProxyClass(KindWomen kindWomen) { this.kindWomen = kindWomen; } public ProxyClass() { this.kindWomen = new PanJinLian(); } public void happyWithMan() { this.kindWomen.happyWithMan(); //自己老了,干不了,可以让年轻的代替 } public void makeEyesWithMan() { this.kindWomen.makeEyesWithMan(); //王婆这么大年龄了,谁看她抛媚眼?! } } public class Ximenqing { public static void main(String[] args) { ProxyClass proxyClass=new ProxyClass(); proxyClass.happyWithMan(); } }
3、单例模式
理解:私有化构造方法、提供一个对外的方法来创建对象
代码实现:
public class SingletonPattern { private static final SingletonPattern single=new SingletonPattern(); public SingletonPattern() { } public synchronized static SingletonPattern getInstance(){ return single; } }
标签:kindWomen,ProxyClass,java23,void,class,学习,设计模式,public,operate From: https://www.cnblogs.com/liubaihui/p/17186865.html