策略模式

已经很久没有写博客了,今天写一篇关于策略模式的。通过交换两个数,来示例策略模式的使用。

package nuc.wss.operation;



/**

 * 交换两个数的接口

 *

 */

public interface Change {

    public void change(long a, long b);

}
View Code
package nuc.wss.operation.impl;



import nuc.wss.operation.Change;

/**

 * 通过加减交换两个数

 *

 */

public class AddOrSub implements Change {



    @Override

    public void change(long a, long b) {

        a = a + b;

        b = a - b;

        a = a - b;

        System.out.println("AddOrSub: a = " + a + " b = " + b);

    }

}
View Code
package nuc.wss.operation.impl;



import nuc.wss.operation.Change;



/**

 * 通过位运算交换两个数

 *

 */

public class BitChange implements Change {



    @Override

    public void change(long a, long b) {

        a = a ^ b;

        b = a ^ b;

        a = a ^ b;

        System.out.println("BitChange: a = " + a + " b = " + b);

    }

}
View Code
package nuc.wss.operation.impl;



import nuc.wss.operation.Change;



/**

 * 通过运算交换两个数

 *

 */

public class OperationChange implements Change {



    @Override

    public void change(long a, long b) {

        a = b + (b = a) * 0;

        System.out.println("OperationChange: a = " + a + " b = " + b);

    }

}
View Code
package nuc.wss.operation.impl;



import nuc.wss.operation.Change;



/**

 * 通过中间变量交换两个数

 *

 */

public class TempChange implements Change {



    @Override

    public void change(long a, long b) {

        long temp = a;

        a = b;

        b = temp;

        System.out.println("TempChange: a = " + a + " b = " + b);

    }



}
View Code
import nuc.wss.operation.Change;



/**

 * 通过此类操作Change子类

 *

 */

public class Context {

    private Change operation;

    

    public Context() {

        

    }

    

    public Context(Change operation) {

        this.operation = operation;

    }

    

    public void setOperation(Change operation) {

        this.operation = operation;

    }

    

    public void operate(long a, long b) {

        operation.change(a, b);

    }

}
View Code
import nuc.wss.operation.impl.AddOrSub;

import nuc.wss.operation.impl.BitChange;

import nuc.wss.operation.impl.OperationChange;

import nuc.wss.operation.impl.TempChange;



public class Main {

    public static void main(String[] args) {

        Context context = new Context();

        

        context.setOperation(new AddOrSub());

        context.operate(3, 4);

        

        context.setOperation(new BitChange());

        context.operate(3, 4);

        

        context.setOperation(new OperationChange());

        context.operate(3, 4);

        

        context.setOperation(new TempChange());

        context.operate(3, 4);

    }

}
View Code

 

你可能感兴趣的:(策略模式)