Java设计模式个人总结(三)

9、策略模式
策略模式定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。需要设计一个接口,为一系列实现类提供统一的方法,多个实现类实现该接口。
下面一个计算器例子代码:
首先统一接口

public interface Calculator {
    public int calculate(String exp);
}

辅助类

public abstract class AbstractCalculator {

    public int[] split(String exp,String opt){
        String array[] = exp.split(opt);
        int arrayInt[] = new int[2];
        arrayInt[0] = Integer.parseInt(array[0]);
        arrayInt[1] = Integer.parseInt(array[1]);
        return arrayInt;
    }
}

三个实现类

public class Plus extends AbstractCalculator implements Calculator {

    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp,"\\+");
        return arrayInt[0]+arrayInt[1];
    }
}

public class Minus extends AbstractCalculator implements Calculator {

    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp,"-");
        return arrayInt[0]-arrayInt[1];
    }

}

public class Multiply extends AbstractCalculator implements Calculator {

    @Override
    public int calculate(String exp) {
        int arrayInt[] = split(exp,"\\*");
        return arrayInt[0]*arrayInt[1];
    }
}

测试类

public class StrategyTest {

    public static void main(String[] args) {
        String exp = "2+8";
        ICalculator cal = new Plus();
        int result = cal.calculate(exp);
        System.out.println(result);
    }
}

策略模式的决定权在用户,系统本身提供不同算法的实现,新增或者删除算法,对各种算法做封装。因此,策略模式多用在算法决策系统中,外部用户只需要决定用哪个算法即可。
10、模版方法模式
模版方法模式在一个方法中定义一个算法的骨架,而将一些步骤的具体实现延迟到子类中。模版方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
下面例子代码:

public abstract class AbstractCalculator {

    /*模版方法,实现对本类其它方法的调用*/
    public final int calculate(String exp,String opt){
        int array[] = split(exp,opt);
        return _calculate(array[0],array[1]);
    }

    /*需要被子类重写的方法*/
    abstract public int _calculate(int num1,int num2);

    public int[] split(String exp,String opt){
        String array[] = exp.split(opt);
        int arrayInt[] = new int[2];
        arrayInt[0] = Integer.parseInt(array[0]);
        arrayInt[1] = Integer.parseInt(array[1]);
        return arrayInt;
    }
}

子类实现_calculate方法

public class Plus extends AbstractCalculator {

    @Override
    public int _calculate(int num1,int num2) {
        return num1 + num2;
    }
}

测试类

public class StrategyTest {

    public static void main(String[] args) {
        String exp = "8+8";
        AbstractCalculator cal = new Plus();
        int result = cal.calculate(exp, "\\+");
        System.out.println(result);
    }
}

模版方法将算法定义成一组步骤,其中的任何步骤都可以是抽象的,由子类负责实现。这可以确保算法的结构不变,同时由子类提供部分实现。
11、观察者模式
观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。
下面例子代码:
一个Observer接口

public interface Observer {
    public void update();
}

两个实现类

public class Observer1 implements Observer {

    @Override
    public void update() {
        System.out.println("observer1 has received!");
    }
}

Subject接口及实现类

public interface Subject {

    /*增加观察者*/
    public void add(Observer observer);

    /*删除观察者*/
    public void del(Observer observer);

    /*通知所有的观察者*/
    public void notifyObservers();

    /*自身的操作*/
    public void operation();
}

public class MySubject implements Subject {

    private Vector<Observer> vector = new Vector<Observer>();
    @Override
    public void add(Observer observer) {
        vector.add(observer);
    }

    @Override
    public void del(Observer observer) {
        vector.remove(observer);
    }

    @Override
    public void notifyObservers() {
        Enumeration<Observer> enumo = vector.elements();
        while(enumo.hasMoreElements()){
            enumo.nextElement().update();
        }
    }

    @Override
    public void operation() {
        System.out.println("update self!");
        notifyObservers();
    }
}

测试类

public class ObserverTest {

    public static void main(String[] args) {
        Subject sub = new MySubject();
        sub.add(new Observer1());
        sub.add(new Observer2());

        sub.operation();
    }

}

Java API有内置的观察者模式。java.util包内包含最基本的Observe接口和Observable类。Java Swing中的各种监听器也应用了监听器模式。
12、命令模式
命令模式有命令的发出者、命令、命令的执行者三个对象,发出者可以发出不同的命令,命令也可以命令不同的执行者。命令模式的目的就是达到命令的发出者和执行者之间解耦,实现请求和执行分开。
下面例子代码:

public interface Command {
    public void execute();
}

public class MyCommand implements Command {

    private Receiver receiver;

    public MyCommand(Receiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.action();
    }
}

public interface Receiver {
    public void action();
}


public class MyReceiver implements Receiver{
    public void action(){
        System.out.println("command received!");
    }
}

public class Invoker {

    private Command command;

    public Invoker(Command command) {
        this.command = command;
    }

    public void action(){
        command.exe();
    }
}

测试类

public class Test {

    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        Command cmd = new MyCommand(receiver);
        Invoker invoker = new Invoker(cmd);
        invoker.action();
    }
}

Java Web框架之一Struts其实就是一种将请求和呈现分离的技术,其中必然涉及命令模式的思想。
13、状态模式
状态模式就是当对象状态改变时,同时改变其行为。这个模式将状态封装成为独立的类,并将动作委托到代表当前状态的对象,行为会随着内部状态而改变。
下面例子代码:

public interface State{
     public void work();
}

public class StateOne{
    @override
    public void work(){
        System.out.println("this is one!")
        }
}

public class StateTwo{
    @override
    public void work(){
        System.out.println("this is two!")
        }
}

Conetext类实现State的转换

public class Context {

    private State state;

    public Context(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public void method() {
        state.work();
    }
}

测试类

public class Test {

    public static void main(String[] args) {

        State stateOne = new StateOne();
        State stateTwo = new StateTwo();
        Context context = new Context(state);

        //设置第一种状态
        state.setValue(stateOne);
        context.method();

        //设置第二种状态
        state.setValue(stateTwo);
        context.method();
    }
}

根据这个特性,状态模式在日常开发中用的挺多的,尤其是做网站的时候,我们有时希望根据对象的某一属性,区别开他们的一些功能,比如说简单的权限控制等。
14、迭代器模式
迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。把游走的任务放在迭代器,而不是聚合上。这样简化了聚合的接口和实现,也让责任各得其所。
下面例子代码:
集合Collection接口和迭代器Iterator接口

public interface Collection {

    public Iterator iterator();

    /*取得集合元素*/
    public Object get(int i);

    /*取得集合大小*/
    public int size();
}

public interface Iterator {
    //前移
    public Object previous();

    //后移
    public Object next();
    public boolean hasNext();

    //取得第一个元素
    public Object first();
}

两个实现

public class MyCollection implements Collection {

    public String string[] = {"A","B","C","D","E"};
    @Override
    public Iterator iterator() {
        return new MyIterator(this);
    }

    @Override
    public Object get(int i) {
        return string[i];
    }

    @Override
    public int size() {
        return string.length;
    }
}

public class MyIterator implements Iterator {

    private Collection collection;
    private int pos = -1;

    public MyIterator(Collection collection){
        this.collection = collection;
    }

    @Override
    public Object previous() {
        if(pos > 0){
            pos--;
        }
        return collection.get(pos);
    }

    @Override
    public Object next() {
        if(pos<collection.size()-1){
            pos++;
        }
        return collection.get(pos);
    }

    @Override
    public boolean hasNext() {
        if(pos<collection.size()-1){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Object first() {
        pos = 0;
        return collection.get(pos);
    }

}

测试类

public class Test {

    public static void main(String[] args) {
        Collection collection = new MyCollection();
        Iterator it = collection.iterator();

        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
}

迭代器在集合中非常常见,如果对集合类比较熟悉的话,理解本模式会十分轻松。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值