您的位置:首页 > 其它

设计模式学习笔记七:策略模式

2015-02-15 11:32 369 查看
策略模式,它主要的作用是封装算法,是一种行为模式。

有三种角色:

1、具体算法角色:具体的算法的实现;

2、抽象策略角色:抽象类或接口,提供具体算法角色的抽象;

3、上下文角色:实现对具体算法角色的引用。

更详细定义参照:策略模式

代码时间:

1、具体实现:

package com.array7.strategy;

public class Run
{
public static void main(String[] args)
{
new Context(new Strategy1()).execute();
new Context(new Strategy2()).execute();
new Context(new Strategy3()).execute();
}
}


2、具体算法策略:

package com.array7.strategy;

public class Strategy1 implements IStrategy {

@Override
public void execute() {
System.out.println("stargtegy1.execute...");
}

}

package com.array7.strategy;

public class Strategy2 implements IStrategy {

@Override
public void execute() {
System.out.println("stargtegy2.execute...");
}

}

package com.array7.strategy;

public class Strategy3 implements IStrategy {

@Override
public void execute() {
System.out.println("stargtegy3.execute...");
}

}


3、抽象接口:

package com.array7.strategy;

public interface IStrategy {
void execute();
}


3、策略引用:

package com.array7.strategy;

public class Context {
private IStrategy strategy;

public Context(IStrategy strategy)
{
this.strategy = strategy;
}
public void execute() {
this.strategy.execute();
}
}


版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: