JAVA设计模式

常用二十三种。


【单例模式】

确保一个类只有一个实例,自行实例化并向整个系统提供这个实例。

● 饿汉式写法(建议):

 

public final class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton() {}
    pbulic static Singleton getInstance() {
        return instance;
    }
}

 ● 懒汉式写法:

public final class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getinstance() {
        if(instance == null) {
            synchronized(Singleton.class) {
                if(instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

【工厂方法模式】

定义一个用于创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。

Creator creator = new ConcreteCreator();
Product product = creator.factory(ConcreteProduct.class);

  【抽象工厂模式】(常见)

为创建一组相关或相互依赖的对象提供一个接口,而且无需指定它们的具体类。

AbstractFactory concreteFactory1 = new ConcreteFactory1();
ProductA productA1 = concreteFactory1.factoryA(ProductA1.class);

 

【建造者模式】

将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

 

public class Director {
    private Builder builder = new ConreteBuilder();
    public Product construct() {
        builder.setPartA();
        builder.setPartB();
        builder.setPartC();
        ...
        return builder.builderProduct();
    }
}

【原型模式】 

用原型实例指定创建对象的种类,并且通过复制这些原型创建新的对象。

public class Client {
    public void operation(Prototype example) {
        Prototype p = example.clone();
    }
}

 【代理模式】(常见)

为其他对象提供一种代理以控制对这个对象的访问。

public class ProxySubject implements Subject {
    private Subject subject;
    public ProxySubject(Subject subject) {
        this.subject = subject;
    }
    public void request() {
        this.beforeRequest();
        subject.request();
        this.afterRequest();
    }
    private void beforeRequest() {...}
    private void afterRequest() {...}
}

 【装饰模式】(常见)

动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比于代理模式生成子类更为灵活。

public class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component); //this.component = component;
    }
    private void decoratorMethod() {...}
    public void operation() {
        this.decoratorMethod();
        super.operation(); //this.component.operation();
    }
}

...使用
Component component = new ConcreteComponent();
component = new ConreteDecorator(component);
component.operation();

 【适配器模式】

将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法一起工作的两个类能够在一起工作。

public class Adapter extends Adaptee implements Target {
    public void request() {
        super.specificRequest();
    }
}
...使用
Target target = new Adapter();
target.request();

 【组合模式】

将对象组合成树形结构以表示“整体-部分”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

Composite root = new Composite();
root.operation();
Composite branch = new Composite();
Leaf leaf = new Leaf();
root.add(branch);
branch.add(leaf);

 【桥梁模式】

将抽象和实现解耦,使得两者可以独立地变化。

Implementor imp = new ConcreteImplementor();
Abstraction abs = new RefinedAbstraction(imp);
abs.operation();

 【外观模式】(常见)

要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行,外观模式提供一个高层次的接口,使得子系统更易使用。
示意图:

public class Facade {
    private ClassA a = new ClassA();
    private ClassB b = new ClassB();
    public void methodA() {
        a.methodA();
    }
    public void methodB() {
        b.methodB();
    }
}

 【享元模式】

使用共享对象有效地支持大量的细粒度的对象。

public class FlyweightFactory {
    private static Map<String, Flyweight> pool = new HashMap<String, Flyweight>();
    private FlyweightFactory(){}
    public static Flyweight getFlyWeight(String intrinsicState) {
        Flyweight flyweight = pool.get(intrinsicState);
        ...
        if null pool.put...
        return flyweight;
    }
}

 【模板方法模式】(常见)

定义一个算法框架,将一些步骤延迟到子类中,使得子类可以在不改变算法结构前提下可重新定义该算法的某些步骤。

public abstract class AbstractClass {
    protected abstract void operation();
    public void templateMethod() {
        this.operation();
    }
}
...
public class ConcreteClass extends AbstractClass {
    @Override
    protected void operation() {...}
}
...使用
AbstractClass ac = new ConcreteClass();
ac.templateMethod();

 【命令模式】

将一个请求封装成一个对象,从面让你能使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。

Invoker invoker = new Invoker();
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
invoker.setCommand(command);
invoker.action();

 【责任链模式】(常见)

使多个对象都有处理请求的机会,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象串连成一条链,并沿着这条链依次传递该请求,直到有对象处理它为止。

Handler h1 = new ConcreteHandler();
Handler h2 = new ConcreteHandler();
hi.setSuccessor(h2);
h1.handleRequest();

【策略模式】

定义一组算法,将每个算法都封装起来,并且例它们之间可以互换。

public class Context {
    private Strategy strategyA = null;
    public Context(Strategy strategy) {
        this.strategyA = strategy;
    }
    public void contextInterface() {
        this.strategyA.strategyInterface();
    }
}

【迭代器模式】(常见)

提供一种方法,访问一个容器对象中的各个元素,而又不需暴露该对象的内部细节。

public class ConcreteAggregate implements Aggregate {
    ...
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
}
...使用
Aggregate agg = new ConcreteAggregate();
agg.add("a");
agg.add("b");
Iterator iterator = agg.creatIterator();
while(iterator.hasNext()) {...}

【中介者模式】

用一个中介对象封装一系列对象的交互,中介者使各对象不需要显式地相互作用,从而使其耦合松散,而且中介者可以独立地改变它们之间的交互。

 

public class ConcreteMediator extends Mediator {
    private ConcreteColleague1 c1;
    ...c2;
    public void colleagueChanged(Colleague c) {
        c1.action();
        c2.action();
    }
    ...
}

public abstract class Colleague {
    private Mediator mediator;
    ...
    public abstract void action();
    public void change() {
        this.mediator.colleagueChanged(this);
    }
}

【观察者模式】(常见)

 定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,所有依赖于它的对象都会得到通知并被自动更新。

public class ConcreteSubject implements Subject {
    private List<Observer> obsVector = Collections.emptyList();
    public void attach(Observer obs) {...}
    public void detach(Observer obs) {...}
    public void notifyObserver() {
        for(Observer e: obsVector) {
            e.update();
        }
    }
    public void change() {
        this.notifyObserver();
    }
}

...使用
ConcreteSubject subject = new ConcreteSubject();
Observer obs = new ConcreteObserver();
subject.attach(obs);
subject.change();

 【备忘录模式】

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

Originator orig= new Originator(); // 发起人
Caretaker car = new Caretaker(); // 负责人
car.setMemento(orig.createMemento()); // 创建一个备忘录
orig.restoreMemento(car.getMemento()); // 恢复一个备忘录

【访问者模式】

封装一些作用于某种数据结构的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新操作。

public class ObjectStructure() {
    private List<Element> elements;
    ...
    public void action(Visitor vi) {
        for(Element e: elements) {
            e.accept(vi);
        }
    }
    ...
}
...使用
ObjectStructure os = new ObjectStructure(); // 创建一个结构对象
os.createElements(); // 生成元素
Visitor vi = new ConcreteVistor(); // 创建一个访问者对象
os.action(vi); // 访问者对结构进行访问

【状态模式】

允许一个对象内在状态发生改变时改变行为,使得这个对象看起来像改变了类型。

public class Context {
    public static State STATE1 = new ConcreteState1();
    public static State STATE2 = new ConcreteState2();
    private State currentState;
    ...
    public void setCurrentState(State currentState) {
        this.currentState = currentState;
        currentState.setContext(this);
    }
    public void handle1() {
        this.setCurrentState(STATE1);
        this.currentState.handle();
    }
    ...
}
...使用
Context context = new Context();
context.handle1();
context.handle2();

【解释器模式】

给定一门语言,定义它的方法的一种表示,并定义一个解释器,该解释器使用该表示方法来解释语言中的句子。

public class NonterminalExpression extends AbstractExpression {
    public NonterminalExpression(AbstractExpression expression) {...}
    @Override
    public Object interpreter(Context ctx) {...}
}

《Java设计模式》拿出来过了一遍,摘一些重点记下来,自己好有个参考,同时也分享出来。

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java设计模式大体上分为三大类: 创建型模式(5种):工厂方法模式,抽象工厂模式,单例模式,建造者模式,原型模式。 结构型模式(7种):适配器模式,装饰器模式,代理模式,外观模式,桥接模式,组合模式,享元模式。 行为型模式(11种):策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。 设计模式遵循的原则有6个: 1、开闭原则(Open Close Principle)   对扩展开放,对修改关闭。 2、里氏代换原则(Liskov Substitution Principle)   只有当衍生类可以替换掉基类,软件单位的功能不受到影响时,基类才能真正被复用,而衍生类也能够在基类的基础上增加新的行为。 3、依赖倒转原则(Dependence Inversion Principle)   这个是开闭原则的基础,对接口编程,依赖于抽象而不依赖于具体。 4、接口隔离原则(Interface Segregation Principle)   使用多个隔离的借口来降低耦合度。 5、迪米特法则(最少知道原则)(Demeter Principle)   一个实体应当尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立。 6、合成复用原则(Composite Reuse Principle)   原则是尽量使用合成/聚合的方式,而不是使用继承。继承实际上破坏了类的封装性,超类的方法可能会被子类修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值