设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
一、设计模式的分类
总体来说设计模式分为三大类:
创建型模式,共五种:工厂方法模式、抽象工厂模式、单例模式、构造者模式、原型模式。
结构型模式,共七种:适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
行为型模式,共十一种:策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
二、设计模式的六大原则
1、开闭原则(Open Close Principle)
开闭原则就是说对扩展开放,对修改关闭。在程序需要进行拓展的时候,不能去修改原有的代码,实现一个热插拔的效果。所以一句话概括就是:为了使程序的扩展性好,易于维护和升级。想要达到这样的效果,我们需要使用接口和抽象类,后面的具体设计中我们会提到这点。
2、里氏代换原则(Liskov Substitution Principle)
里氏代换原则(Liskov Substitution Principle LSP)面向对象设计的基本原则之一。 里氏代换原则中说,任何基类可以出现的地方,子类一定可以出现。 LSP是继承复用的基石,只有当衍生类可以替换掉基类,软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。里氏代换原则是对“开-闭”原则的补充。实现“开-闭”原则的关键步骤就是抽象化。而基类与子类的继承关系就是抽象化的具体实现,所以里氏代换原则是对实现抽象化的具体步骤的规范。—— From Baidu 百科
3、依赖倒转原则(Dependence Inversion Principle)
这个是开闭原则的基础,具体内容:真对接口编程,依赖于抽象而不依赖于具体。
4、接口隔离原则(Interface Segregation Principle)
这个原则的意思是:使用多个隔离的接口,比使用单个接口要好。还是一个降低类之间的耦合度的意思,从这儿我们看出,其实设计模式就是一个软件的设计思想,从大型软件架构出发,为了升级和维护方便。所以上文中多次出现:降低依赖,降低耦合。
5、迪米特法则(最少知道原则)(Demeter Principle)
为什么叫最少知道原则,就是说:一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。
6、合成复用原则(Composite Reuse Principle)
原则是尽量使用合成/聚合的方式,而不是使用继承。
下面是实例源码,使用内部类实现是方便复制编译运行查看效果:
创建型模式,共五种:
1、工厂方法模式(factorymethod)
定义一个用于创建对象的接口,让子类决定实例化哪一个类。FactoryMethod使一个类的实例化延迟到其子类。
package com.jiepu;
public class Testfactorymethod {
interface Sender {
public void Send();
}
class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is mail sender!");
}
}
class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
static class SendFactory {
public static Sender produceMail() {
return new Testfactorymethod().new MailSender();
}
public static Sender produceSms() {
return new Testfactorymethod().new SmsSender();
}
}
public static void main(String[] args) {
Sender sender = SendFactory.produceMail();
sender.Send();
SendFactory.produceSms().Send();
}
}
2、抽象工厂模式(abstractfactory)
提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
package com.jiepu;
public class Testabstractfactory {
interface Sender {
public void Send();
}
interface Factory {
public Sender produce();
}
class MailSender implements Sender {
@Override
public void Send() {
System.out.println("this is email sender!");
}
}
class SmsSender implements Sender {
@Override
public void Send() {
System.out.println("this is sms sender!");
}
}
class SendSmsFactory implements Factory {
@Override
public Sender produce() {
return new SmsSender();
}
}
class SendMailFactory implements Factory {
@Override
public Sender produce(){
return new MailSender();
}
}
public static void main(String[] args) {
Factory factory = new Testabstractfactory().new SendMailFactory();
Sender sender = factory.produce();
sender.Send();
new Testabstractfactory().new SendSmsFactory().produce().Send();
}
}
3、单例模式(Singleton)
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
package com.jiepu;
//http://blog.youkuaiyun.com/zhangerqing/article/details/8194653
public class Singleton {
/* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
private static Singleton instance = null;
/* 私有构造方法,防止被实例化 */
private Singleton() {
}
/* 静态工程方法,创建实例 */
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {//synchronized关键字锁定的是对象
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
public static Singleton getInstance2() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new Singleton();
}
}
public static Singleton getInstance3() {
if (instance == null) {
syncInit();
}
return instance;
}
/* 此处使用一个内部类来维护单例 */
private static class SingletonFactory {
private static Singleton instance = new Singleton();
}
/* 获取实例 */
public static Singleton getInstance4() {
return SingletonFactory.instance;
}
/* 如果该对象被用于序列化,可以保证对象在序列化前后保持一致 */
public Object readResolve() {
return instance;
}
}
4、构造者模式(Builder)
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
package com.jiepu;
public class TestBuilder {
interface PersonBuilder {
void buildHead();
void buildBody();
void buildFoot();
Person buildPerson();
}
class Person {
private String head;
private String body;
private String foot;
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getFoot() {
return foot;
}
public void setFoot(String foot) {
this.foot = foot;
}
}
class Man extends Person {
}
class ManBuilder implements PersonBuilder {
Person person;
public ManBuilder() {
person = new Man();
}
@Override
public void buildBody() {
person.setBody("建造男人的身体");
}
public void buildFoot() {
person.setFoot("建造男人的脚");
}
public void buildHead() {
person.setHead("建造男人的头");
}
public Person buildPerson() {
return person;
}
}
class PersonDirector {
public Person constructPerson(PersonBuilder pb) {
pb.buildHead();
pb.buildBody();
pb.buildFoot();
return pb.buildPerson();
}
}
public static void main(String[] args) {
PersonDirector pd = new TestBuilder().new PersonDirector();
Person person = pd.constructPerson(new TestBuilder().new ManBuilder());
System.out.println(person.getBody());
System.out.println(person.getFoot());
System.out.println(person.getHead());
}
}
5、原型模式(Prototype)。
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
package com.jiepu;
public class TestPrototype {
class Prototype implements Cloneable {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public Object clone(){
try {
return super.clone();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
class ConcretePrototype extends Prototype {
public ConcretePrototype(String name) {
setName(name);
}
}
public static void main(String[] args) {
Prototype pro = new TestPrototype().new ConcretePrototype("prototype_");
Prototype pro2 = (Prototype)pro.clone();
System.out.println(pro.getName());
System.out.println(pro2.getName());
}
}
结构型模式,共七种:
1、适配器模式(Adapter)
将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
package com.jiepu;
public class TestAdapter {
interface Target {
void adapteeMethod();
void adapterMethod();
}
class Adaptee{
public void adapteeMethod() {
System.out.println("Adaptee method!");
}
}
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void adapteeMethod() {
adaptee.adapteeMethod();
}
public void adapterMethod() {
System.out.println("Adapter method!");
}
}
public static void main(String[] args) {
Target target = new TestAdapter().new Adapter(new TestAdapter().new Adaptee());
target.adapteeMethod();
target.adapterMethod();
}
}
2、装饰器模式(Decorator)
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
package com.jiepu;
public class TestDecorator {
interface Person {
void eat();
}
class Man implements Person {
public void eat() {
System.out.println("男人在吃");
}
}
abstract class Decorator implements Person {
protected Person person;
public void setPerson(Person person) {
this.person = person;
}
public void eat() {
person.eat();
}
}
class ManDecoratorA extends Decorator {
public void eat() {
super.eat();
reEat();
System.out.println("ManDecoratorA类");
}
public void reEat() {
System.out.println("再吃一顿饭");
}
}
class ManDecoratorB extends Decorator {
public void eat() {
super.eat();
System.out.println("===============");
System.out.println("ManDecoratorB类");
}
}
public static void main(String[] args) {
Man man = new TestDecorator().new Man();
ManDecoratorA md1 = new TestDecorator().new ManDecoratorA();
ManDecoratorB md2 = new TestDecorator().new ManDecoratorB();
md1.setPerson(man);
md2.setPerson(md1);
md2.eat();
}
}
3、代理模式(Proxy)
为其他对象提供一种代理以控制对这个对象的访问。
package com.jiepu;
public class TestProxy {
abstract class Subject {
abstract void request();
}
class RealSubject extends Subject {
public RealSubject() {
}
public void request() {
System.out.println("From real subject.");
}
}
class ProxySubject extends Subject {
private RealSubject realSubject; // 以真实角色作为代理角色的属性
public ProxySubject() {
}
public void request() { // 该方法封装了真实对象的request 方法
preRequest();
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.request(); // 此处执行真实对象的request 方法
postRequest();
}
private void postRequest() {
System.out.println("代理执行之前");
}
private void preRequest() {
System.out.println("代理执行之后");
}
}
public static void main(String[] args) {
Subject sub = new TestProxy().new ProxySubject();
sub.request();
}
}
package com.jiepu;
public class TestProxy2 {
interface Object {
void action();
}
class ObjectImpl implements Object {
public void action() {
System.out.println("========");
System.out.println("========");
System.out.println("这是被代理的类");
System.out.println("========");
System.out.println("========");
}
}
class ProxyObject implements Object {
Object obj;
public ProxyObject() {
System.out.println("这是代理类");
obj = new ObjectImpl();
}
public void action() {
System.out.println("代理开始");
obj.action();
System.out.println("代理结束");
}
}
public static void main(String[] args) {
Object obj = new TestProxy2().new ProxyObject();
obj.action();
}
}
4、外观模式(Facade)
为子系统中的一组接口提供一个一致的界面,Facade模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
package com.jiepu;
public class TestFacade {
interface ServiceA {
public void methodA();
}
interface ServiceB {
public void methodB();
}
interface ServiceC {
public void methodC();
}
class ServiceAImpl implements ServiceA {
public void methodA() {
System.out.println("这是服务A");
}
}
class ServiceBImpl implements ServiceB {
public void methodB() {
System.out.println("这是服务B");
}
}
class ServiceCImpl implements ServiceC {
public void methodC() {
System.out.println("这是服务C");
}
}
ServiceA sa;
ServiceB sb;
ServiceC sc;
public TestFacade() {
sa = new ServiceAImpl();
sb = new ServiceBImpl();
sc = new ServiceCImpl();
}
public void methodA() {
sa.methodA();
sb.methodB();
}
public void methodB() {
sb.methodB();
sc.methodC();
}
public void methodC() {
sc.methodC();
sa.methodA();
}
public static void main(String[] args) {
ServiceA sa = new TestFacade().new ServiceAImpl();
ServiceB sb = new TestFacade().new ServiceBImpl();
sa.methodA();
sb.methodB();
System.out.println("========");
// facade
TestFacade facade = new TestFacade();
facade.methodA();
facade.methodB();
}
}
5、桥接模式(Bridge)
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
package com.jiepu;
public class TestBridge {
abstract class Clothing {
public abstract void personDressCloth(Person person);
}
abstract class Person {
private Clothing clothing;
private String type;
public Clothing getClothing() {
return clothing;
}
public void setClothing(Clothing clothing) {
this.clothing = clothing;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return this.type;
}
public abstract void dress();
}
class Jacket extends Clothing {
public void personDressCloth(Person person) {
System.out.println(person.getType() + "穿马甲");
}
}
class Trouser extends Clothing {
public void personDressCloth(Person person) {
System.out.println(person.getType() + "穿裤子");
}
}
class Man extends Person {
public Man() {
setType("男人");
}
public void dress() {
Clothing clothing = getClothing();
clothing.personDressCloth(this);
}
}
class Lady extends Person {
public Lady() {
setType("女人");
}
public void dress() {
Clothing clothing = getClothing();
clothing.personDressCloth(this);
}
}
public static void main(String[] args) {
Person man = new TestBridge().new Man();
Person lady = new TestBridge().new Lady();
Clothing jacket = new TestBridge().new Jacket();
Clothing trouser = new TestBridge().new Trouser();
jacket.personDressCloth(man);
trouser.personDressCloth(man);
jacket.personDressCloth(lady);
trouser.personDressCloth(lady);
}
}
6、组合模式(Composite)
将对象组合成树形结构以表示"部分-整体"的层次结构。Composite使得用户对单个对象和组合对象的使用具有一致性。
package com.jiepu;
import java.util.ArrayList;
import java.util.List;
public class TestComposite {
abstract class Employer {
public abstract void add(Employer employer);
public abstract void delete(Employer employer);
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void printInfo() {
System.out.println(name);
}
public List employers;
public List getEmployers() {
return this.employers;
}
}
class Programmer extends Employer {
public Programmer(String name) {
setName(name);
employers = null;// 程序员, 表示没有下属了
}
public void add(Employer employer) {}
public void delete(Employer employer) {}
}
class ProjectAssistant extends Employer {
public ProjectAssistant(String name) {
setName(name);
employers = null;// 项目助理, 表示没有下属了
}
public void add(Employer employer) {}
public void delete(Employer employer) {}
}
class ProjectManager extends Employer {
public ProjectManager(String name) {
setName(name);
employers = new ArrayList();
}
public void add(Employer employer) {
employers.add(employer);
}
public void delete(Employer employer) {
employers.remove(employer);
}
}
public static void main(String[] args) {
Employer pm = new TestComposite().new ProjectManager("项目经理");
Employer pa = new TestComposite().new ProjectAssistant("项目助理");
Employer programmer1 = new TestComposite().new Programmer("程序员一");
Employer programmer2 = new TestComposite().new Programmer("程序员二");
pm.add(pa);// 为项目经理添加项目助理
pm.add(programmer2);// 为项目经理添加程序员
pm.add(programmer1);
List<Employer> ems = pm.getEmployers();
for (Employer em : ems) {
System.out.println(em.getName());
}
}
}
7、享元模式(Flyweight)
运用共享技术有效地支持大量细粒度的对象。
package com.jiepu;
import java.util.HashMap;
import java.util.Map;
public class TestFlyweight {
interface Flyweight {
void action(int arg);
}
class FlyweightImpl implements Flyweight {
public void action(int arg) {
System.out.println("参数值: " + arg);
}
}
//有静态成员变量 所以需要静态类
static class FlyweightFactory {
private static Map flyweights = new HashMap();
public FlyweightFactory(String arg) {
flyweights.put(arg, new TestFlyweight().new FlyweightImpl());
}
public static Flyweight getFlyweight(String key) {
if (flyweights.get(key) == null) {
flyweights.put(key, new TestFlyweight().new FlyweightImpl());
}
return (Flyweight) flyweights.get(key);
}
public static int getSize() {
return flyweights.size();
}
}
public static void main(String[] args) {
Flyweight fly1 = FlyweightFactory.getFlyweight("a");
fly1.action(1);
Flyweight fly2 = FlyweightFactory.getFlyweight("a");
System.out.println(fly1 == fly2);
Flyweight fly3 = FlyweightFactory.getFlyweight("b");
fly3.action(2);
Flyweight fly4 = FlyweightFactory.getFlyweight("c");
fly4.action(3);
Flyweight fly5 = FlyweightFactory.getFlyweight("d");
fly4.action(4);
System.out.println(FlyweightFactory.getSize());
}
}
行为型模式,共十一种:
1、策略模式(Strategy)
定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
package com.jiepu;
public class TestStrategy {
abstract class Strategy {
public abstract void method();
}
class StrategyImplA extends Strategy {
public void method() {
System.out.println("这是第一个实现a");
}
}
class StrategyImplB extends Strategy {
public void method() {
System.out.println("这是第二个实现b");
}
}
class StrategyImplC extends Strategy {
public void method() {
System.out.println("这是第三个实现c");
}
}
class Context {
Strategy stra;
public Context(Strategy stra) {
this.stra = stra;
}
public void doMethod() {
stra.method();
}
}
public static void main(String[] args) {
// 策略模式:同样的接口调用不同的方法实现。
// 策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。
Context ctx = new TestStrategy().new Context(new TestStrategy().new StrategyImplA());
ctx.doMethod();
ctx = new TestStrategy().new Context(new TestStrategy().new StrategyImplB());
ctx.doMethod();
ctx = new TestStrategy().new Context(new TestStrategy().new StrategyImplC());
ctx.doMethod();
}
}
2、模板方法模式(TemplateMethod)
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。TemplateMethod使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
package com.jiepu;
public class TestTemplate {
abstract class Template {
public abstract void print();
public void update() {
System.out.println("开始打印");
for (int i = 0; i < 10; i++) {
print();
}
}
}
class TemplateConcrete extends Template {
@Override
public void print() {
System.out.println("这是子类的实现,我去抓取");
}
}
public static void main(String[] args) {
Template temp = new TestTemplate().new TemplateConcrete();
temp.update();
}
}
3、观察者模式(Observer)
定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
package com.jiepu;
import java.util.ArrayList;
import java.util.List;
public class TestObserver {
interface Policeman {
void action(Citizen ci);
}
abstract class Citizen {
List pols;
String help = "normal";
public void setHelp(String help) {
this.help = help;
}
public String getHelp() {
return this.help;
}
abstract void sendMessage(String help);
public void setPolicemen() {
this.pols = new ArrayList();
}
public void register(Policeman pol) {
this.pols.add(pol);
}
public void unRegister(Policeman pol) {
this.pols.remove(pol);
}
}
class HuangPuCitizen extends Citizen {
public HuangPuCitizen(Policeman pol) {
setPolicemen();
register(pol);
}
public void sendMessage(String help) {
setHelp(help);
for (int i = 0; i < pols.size(); i++) {
Policeman pol = (Policeman) pols.get(i);
// 通知警察行动
pol.action(this);
}
}
}
class TianHeCitizen extends Citizen {
public TianHeCitizen(Policeman pol) {
setPolicemen();
register(pol);
}
public void sendMessage(String help) {
setHelp(help);
for (int i = 0; i < pols.size(); i++) {
Policeman pol = (Policeman) pols.get(i);
// 通知警察行动
pol.action(this);
}
}
}
class TianHePoliceman implements Policeman {
public void action(Citizen ci) {
String help = ci.getHelp();
if (help.equals("normal")) {
System.out.println("一切正常, 不用出动");
}
if (help.equals("unnormal")) {
System.out.println("有犯罪行为, 天河警察出动!");
}
}
}
class HuangPuPoliceman implements Policeman {
public void action(Citizen ci) {
String help = ci.getHelp();
if (help.equals("normal")) {
System.out.println("一切正常, 不用出动");
}
if (help.equals("unnormal")) {
System.out.println("有犯罪行为, 黄埔警察出动!");
}
}
}
public static void main(String[] args) {
Policeman thPol = new TestObserver().new TianHePoliceman();
Policeman hpPol = new TestObserver().new HuangPuPoliceman();
Citizen citizen = new TestObserver().new HuangPuCitizen(hpPol);
citizen.sendMessage("unnormal");
citizen.sendMessage("normal");
System.out.println("===========");
citizen = new TestObserver().new TianHeCitizen(thPol);
citizen.sendMessage("normal");
citizen.sendMessage("unnormal");
}
}
4、迭代器模式(Iterator)
提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
package com.jiepu;
public class TestIterator {
interface Iterator {
Object next();
void first();
void last();
boolean hasNext();
}
interface List {
Iterator iterator();
Object get(int index);
int getSize();
void add(Object obj);
}
class IteratorImpl implements Iterator {
private List list;
private int index;
public IteratorImpl(List list) {
index = 0;
this.list = list;
}
public void first() {
index = 0;
}
public void last() {
index = list.getSize();
}
public Object next() {
Object obj = list.get(index);
index++;
return obj;
}
public boolean hasNext() {
return index < list.getSize();
}
}
class ListImpl implements List {
private Object[] list;
private int index;
private int size;
public ListImpl() {
index = 0;
size = 0;
list = new Object[100];
}
public Iterator iterator() {
return new IteratorImpl(this);
}
public Object get(int index) {
return list[index];
}
public int getSize() {
return this.size;
}
public void add(Object obj) {
list[index++] = obj;
size++;
}
}
public static void main(String[] args) {
List list = new TestIterator().new ListImpl();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
//第一种迭代方式
Iterator it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("=====");
//第二种迭代方式
for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}
}
}
5、责任链模式(chainofresponsibility)
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。这一模式的想法是,给多个对象处理一个请求的机会,从而解耦发送者和接受者.
package com.jiepu;
public class TestChainofresponsibility {
interface Request {
void dorequest();
}
interface RequestHandle {
void handleRequest(Request request);
}
class AddMoneyRequest implements Request {
@Override
public void dorequest() {
System.out.println("请求加薪");
}
}
class DimissionRequest implements Request {
@Override
public void dorequest() {
System.out.println("请求离职");
}
}
class LeaveRequest implements Request {
@Override
public void dorequest() {
System.out.println("有事请假");
}
}
class HRRequestHandle implements RequestHandle {
public void handleRequest(Request request) {
if (request instanceof DimissionRequest) {
System.out.println("要离职, 人事审批!");
}
System.out.println("请求完毕");
}
}
class PMRequestHandle implements RequestHandle {
RequestHandle rh;
public PMRequestHandle(RequestHandle rh) {
this.rh = rh;
}
public void handleRequest(Request request) {
if (request instanceof AddMoneyRequest) {
System.out.println("要加薪, 项目经理审批!");
} else {
rh.handleRequest(request);
}
}
}
class TLRequestHandle implements RequestHandle {
RequestHandle rh;
public TLRequestHandle(RequestHandle rh) {
this.rh = rh;
}
public void handleRequest(Request request) {
if (request instanceof LeaveRequest) {
System.out.println("要请假, 项目组长审批!");
} else {
rh.handleRequest(request);
}
}
}
public static void main(String[] args) {
RequestHandle hr = new TestChainofresponsibility().new HRRequestHandle();
RequestHandle pm = new TestChainofresponsibility().new PMRequestHandle(hr);
RequestHandle tl = new TestChainofresponsibility().new TLRequestHandle(pm);
// team leader处理离职请求
Request request = new TestChainofresponsibility().new DimissionRequest();
tl.handleRequest(request);
System.out.println("===========");
// team leader处理加薪请求
request = new TestChainofresponsibility().new AddMoneyRequest();
tl.handleRequest(request);
System.out.println("========");
// 项目经理上理辞职请求
request = new TestChainofresponsibility().new DimissionRequest();
pm.handleRequest(request);
}
}
6、命令模式(Command)
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
package com.jiepu;
public class TestCommand {
abstract class Command {
protected Receiver receiver;
public Command(Receiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
class CommandImpl extends Command {
public CommandImpl(Receiver receiver) {
super(receiver);
}
public void execute() {
receiver.receive();
}
}
class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void execute() {
command.execute();
}
}
class Receiver {
public void receive() {
System.out.println("This is Receive class!");
}
}
public static void main(String[] args) {
Receiver rec = new TestCommand().new Receiver();
Command cmd = new TestCommand().new CommandImpl(rec);
Invoker i = new TestCommand().new Invoker();
i.setCommand(cmd);
i.execute();
}
}
7、备忘录模式(Memento)
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
package com.jiepu;
public class TestMemento {
class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
class Originator {
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Memento createMemento() {
return new Memento(state);
}
public void setMemento(Memento memento) {
state = memento.getState();
}
public void showState() {
System.out.println(state);
}
}
class Caretaker {
private Memento memento;
public Memento getMemento() {
return this.memento;
}
public void setMemento(Memento memento) {
this.memento = memento;
}
}
public static void main(String[] args) {
Originator org =new TestMemento(). new Originator();
org.setState("开会中");
org.showState();
Caretaker ctk = new TestMemento(). new Caretaker();
ctk.setMemento(org.createMemento());// 将数据封装在Caretaker
org.setState("睡觉中");
org.showState();// 显示
org.setMemento(ctk.getMemento());// 将数据重新导入
org.showState();
}
}
8、状态模式(State)
允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类
package com.jiepu;
public class TestState {
interface Weather {
String getWeather();
}
class Context {
private Weather weather;
public void setWeather(Weather weather) {
this.weather = weather;
}
public Weather getWeather() {
return this.weather;
}
public String weatherMessage() {
return weather.getWeather();
}
}
class Rain implements Weather {
public String getWeather() {
return "下雨";
}
}
class Sunshine implements Weather {
public String getWeather() {
return "阳光";
}
}
public static void main(String[] args) {
Context ctx1 =new TestState().new Context();
ctx1.setWeather(new TestState().new Sunshine());
System.out.println(ctx1.weatherMessage());
ctx1.setWeather(new TestState().new Rain());
System.out.println(ctx1.weatherMessage());
System.out.println("===============");
Context ctx2 = new TestState().new Context();
ctx2.setWeather(new TestState().new Rain());
System.out.println(ctx2.weatherMessage());
}
}
9、访问者模式(Visitor)
表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
package com.jiepu;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class TestVisitor {
interface Visitor {
public void visitString(StringElement stringE);
public void visitFloat(FloatElement floatE);
public void visitCollection(Collection collection);
}
interface Visitable {
public void accept(Visitor visitor);
}
class StringElement implements Visitable {
private String se;
public StringElement(String se) {
this.se = se;
}
public String getSe() {
return this.se;
}
public void accept(Visitor visitor) {
visitor.visitString(this);
}
}
class FloatElement implements Visitable {
private Float fe;
public FloatElement(Float fe) {
this.fe = fe;
}
public Float getFe() {
return this.fe;
}
public void accept(Visitor visitor) {
visitor.visitFloat(this);
}
}
class ConcreteVisitor implements Visitor {
public void visitCollection(Collection collection) {
// TODO Auto-generated method stub
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object o = iterator.next();
if (o instanceof Visitable) {
((Visitable)o).accept(this);
}
}
}
public void visitFloat(FloatElement floatE) {
System.out.println(floatE.getFe());
}
public void visitString(StringElement stringE) {
System.out.println(stringE.getSe());
}
}
public static void main(String[] args) {
Visitor visitor = new TestVisitor().new ConcreteVisitor();
StringElement se = new TestVisitor().new StringElement("abc");
se.accept(visitor);
FloatElement fe = new TestVisitor().new FloatElement(new Float(1.5));
fe.accept(visitor);
System.out.println("===========");
List result = new ArrayList();
result.add(new TestVisitor().new StringElement("abcd"));
result.add(new TestVisitor().new StringElement("abcde"));
result.add(new TestVisitor().new StringElement("abcdef"));
result.add(new TestVisitor().new FloatElement(new Float(2.5)));
result.add(new TestVisitor().new FloatElement(new Float(3.5)));
result.add(new TestVisitor().new FloatElement(new Float(4.5)));
visitor.visitCollection(result);
}
}
10、中介者模式(Mediator)
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
package com.jiepu;
public class TestMediator {
abstract class Mediator {
public abstract void notice(String content);
}
abstract class Colleague {
public abstract void action();
}
class ColleagueA extends Colleague {
public void action() {
System.out.println("普通员工努力工作");
}
}
class ColleagueB extends Colleague {
public void action() {
System.out.println("前台注意了!");
}
}
class ConcreteMediator extends Mediator {
private ColleagueA ca;
private ColleagueB cb;
public ConcreteMediator() {
ca = new ColleagueA();
cb = new ColleagueB();
}
public void notice(String content) {
if (content.equals("boss")) {
// 老板来了, 通知员工A
ca.action();
}
if (content.equals("client")) {
// 客户来了, 通知前台B
cb.action();
}
}
}
public static void main(String[] args) {
Mediator med =new TestMediator(). new ConcreteMediator();
// 老板来了
med.notice("boss");
// 客户来了
med.notice("client");
}
}
11、解释器模式(Interpreter)
给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
package com.jiepu;
import java.util.ArrayList;
import java.util.List;
public class TestInterpreter {
abstract class Expression {
abstract void interpret(Context ctx);
}
class AdvanceExpression extends Expression {
void interpret(Context ctx) {
System.out.println("这是高级解析器!");
}
}
class SimpleExpression extends Expression {
void interpret(Context ctx) {
System.out.println("这是普通解析器!");
}
}
class Context {
private String content;
private List list = new ArrayList();
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return this.content;
}
public void add(Expression eps) {
list.add(eps);
}
public List getList() {
return list;
}
}
public static void main(String[] args) {
Context ctx = new TestInterpreter().new Context();
ctx.add(new TestInterpreter().new SimpleExpression());
ctx.add(new TestInterpreter().new AdvanceExpression());
ctx.add(new TestInterpreter().new SimpleExpression());
for (Expression eps : (List<Expression>) ctx.getList()) {
eps.interpret(ctx);
}
}
}
http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html
http://blog.youkuaiyun.com/zhangerqing/article/details/8194653
源码下载: