单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
public class Singleton { private static volatile Singleton singleton; private Singleton(){} public static Singleton getInstance(){ if(singleton==null){ synchronized (Singleton.class){ if(singleton==null){ singleton=new Singleton(); } } } return singleton; } }
代理模式:为其他对象提供一种代理以控制对这个对象的访问。
interface Workday{ void driver(); void goShopping(); void coding(); } class LazyGirl{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } class Me implements Workday{ LazyGirl gy ; public Me(LazyGirl gy){ this.gy=gy; } @Override public void driver() { System.out.println("驾驶"); } @Override public void goShopping() { System.out.println("购物"); } @Override public void coding() { System.out.println("写代码"); } } public class ProxyFriend implements Workday{ private Me me; public ProxyFriend(LazyGirl girl){ me = new Me(girl); } @Override public void driver() { System.out.println("代理驾驶"); } @Override public void goShopping() { System.out.println("代理购物"); } @Override public void coding() { System.out.println("代理写代码"); } public static void main(String[] args){ LazyGirl gy = new LazyGirl(); gy.setName("小娅"); ProxyFriend lanlan = new ProxyFriend(gy); //代理岚岚不认识懒女孩我,却可以替我work lanlan.coding(); lanlan.goShopping(); lanlan.driver(); } }
装饰模式:是为已有功能动态地添加更多功能的一种方式。它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择、按顺序地使用装饰功能包装对象。
public class Brother { private String name; public Brother(){}; public Brother(String name){ this.name=name; } public void show(){ System.out.println("装饰弟弟"); } public static void main(String[] args){ Brother brother= new Brother("gyang"); DownJacket dj = new DownJacket(); Jeans jeans = new Jeans(); RedCollar rc = new RedCollar(); dj.Decorate(brother); jeans.Decorate(dj); rc.Decorate(jeans); rc.show(); } } class Clothes extends Brother{ private Brother brother; public Clothes() {}; public void Decorate(Brother brother){ //衣服装饰弟弟 this.brother=brother; } public void show(){ brother.show();; } } class DownJacket extends Clothes{ @Override public void show() { System.out.println("羽绒服"); super.show(); } } class MartinBoots extends Clothes{ @Override public void show() { System.out.println("马丁靴"); super.show(); } } class Jeans extends Clothes{ @Override public void show() { System.out.println("牛仔裤"); super.show(); } } class RedCollar extends Clothes{ @Override public void show() { System.out.println("红围脖"); super.show(); } }
策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
//抽象算法类 abstract class Strategy { public abstract void AlgorithmInterface(); } //具体算法A class ConcreteStrategyA extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法A实现"); } } //具体算法B class ConcreteStrategyB extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法B实现"); } } //具体算法C class ConcreteStrategyC extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法B实现"); } } class Context{ Strategy strategy; public Context(Strategy strategy){ this.strategy=strategy; } public void ContextInterface(){ strategy.AlgorithmInterface(); } } public class Test { static void main(String[] args){ Context context = new Context(new ConcreteStrategyA()); context.ContextInterface(); } }
模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到之类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
abstract class AbstractClass{ public abstract void PrimitiveOperation1(); public abstract void PrimitiveOperation2(); public void TemplateMethod(){ PrimitiveOperation1(); PrimitiveOperation2(); } } class ConcreteClassA extends AbstractClass{ @Override public void PrimitiveOperation1() { System.out.println("具体类A方法1实现"); } @Override public void PrimitiveOperation2() { System.out.println("具体类A方法2实现"); } } class ConcreteClassB extends AbstractClass{ @Override public void PrimitiveOperation1() { System.out.println("具体类B方法1实现"); } @Override public void PrimitiveOperation2() { System.out.println("具体类B方法2实现"); } } public class TestTemplateMethod { public static void main(String[] args){ AbstractClass c ; c= new ConcreteClassA(); c.TemplateMethod(); c= new ConcreteClassB(); c.TemplateMethod(); } }
外观模式:为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
何时使用最好?三个阶段。首先设计初期阶段,应该有意识的将不同的两个层分离,考虑层与层之间建立外观Facade。其次开发阶段。第三,维护阶段。
class SubSystemOne{ public void MethodOne(){ System.out.println("子系统方法一"); } } class SubSystemTwo{ public void MethodTwo(){ System.out.println("子系统方法二"); } } class SubSystemThree{ public void MethodThree(){ System.out.println("子系统方法三"); } } public class TestFacade { SubSystemOne one ; SubSystemTwo two; SubSystemThree three; public TestFacade(){ one = new SubSystemOne(); two = new SubSystemTwo(); three = new SubSystemThree(); } public void MethodA(){ one.MethodOne(); two.MethodTwo(); } public void MethodB(){ three.MethodThree(); two.MethodTwo(); } public static void main(String[] args){ TestFacade facade = new TestFacade(); facade.MethodA(); facade.MethodB(); } }
建造者模式:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
import java.util.ArrayList; import java.util.List; //产品类 class Product{ List<String> parts = new ArrayList<String>(); public void Add(String parts){} public void Show(){} } //抽象建造者 abstract class Builder{ public abstract void BuildPartA(); public abstract void BuildPartB(); public abstract Product GetResult(); } //具体建造者 class ConcreteBuilder1 extends Builder{ private Product product = new Product(); @Override public void BuildPartA() { product.Add("部件A"); } @Override public void BuildPartB() { product.Add("部件B"); } @Override public Product GetResult() { return product; } } //具体建造者 class ConcreteBuilder2 extends Builder{ private Product product = new Product(); @Override public void BuildPartA() { product.Add("部件X"); } @Override public void BuildPartB() { product.Add("部件Y"); } @Override public Product GetResult() { return product; } } //指挥者类 class Director{ public void Construct(Builder builder){ builder.BuildPartA(); builder.BuildPartB(); } } public class TestBuilder { public static void main(String[] args){ Director director = new Director(); Builder b1 = new ConcreteBuilder1(); Builder b2 = new ConcreteBuilder2(); director.Construct(b1); Product p1 = b1.GetResult(); p1.Show(); } }
观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发送改变时会通知所有观察者对象,使它们能够自动更新自己。
import java.util.ArrayList; import java.util.List; //抽象通知者 abstract class Subject{ private List<Observer> observers = new ArrayList<Observer>(); //增加观察者 public void Attach(Observer observer){ observers.add(observer); } //移除观察者 public void Detach(Observer observer){ observers.remove(observer); } //通知 public void Notify(){ for(Observer o :observers){ o.Update(); } } } //抽象观察者 abstract class Observer{ public abstract void Update(); } class ConcreteSubject extends Subject{ private String subjectState; public String getSubjectState() { return subjectState; } public void setSubjectState(String subjectState) { this.subjectState = subjectState; } } class ConcreteObserver extends Observer{ private ConcreteSubject subject; private String observerState; private String name; public ConcreteObserver(ConcreteSubject subject,String name){ this.subject = subject; this.name = name; } public ConcreteSubject getSubject() { return subject; } public void setSubject(ConcreteSubject subject) { this.subject = subject; } @Override public void Update() { observerState = subject.getSubjectState(); } } public class TestObserver { public static void main(String[] args){ ConcreteSubject s = new ConcreteSubject(); s.Attach(new ConcreteObserver(s,"X")); s.Attach(new ConcreteObserver(s,"Y")); s.setSubjectState("AAA"); s.Notify(); } }
状态模式:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
//抽象状态类 abstract class State{ public abstract void Handle(Context context); } class Context{ private State state; public Context(State state){ this.state=state; } public void Request(){ state.Handle(this); System.out.println("1"); } public State getState() { return state; } public void setState(State state) { this.state = state; } } //具体状态A class ConcreteStateA extends State{ @Override public void Handle(Context context) { context.setState(new ConcreteStateB()); System.out.println("执行状态A"); } } //具体状态B class ConcreteStateB extends State{ @Override public void Handle(Context context) { context.setState(new ConcreteStateA()); System.out.println("执行状态B"); } } public class TestState { public static void main(String[] args){ Context c = new Context(new ConcreteStateA());//设置Context的初始状态为ConcreteStateA c.Request(); c.Request();//不断请求,同时更改状态 } }
适配器模式:系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
//客户所期待的接口,目标可以是具体的或抽象的类,也可以是接口。 class Target{ public void Request(){ System.out.println("普通请求"); } } //相当于翻译 class Adapter extends Target{ private Adaptee adaptee= new Adaptee(); public void Request(){ adaptee.SpecialRequest(); } } //相当于姚明,需要适配的类 class Adaptee{ public void SpecialRequest(){ System.out.println("特殊请求,需要适配的类"); } } public class TestAdapter { public static void main(String[] args){ Target target = new Adapter(); target.Request(); } }