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

来源:互联网 发布:mac系统盘在哪 编辑:程序博客网 时间:2024/05/16 18:10

策略模式,它主要的作用是封装算法,是一种行为模式。

有三种角色:

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 {@Overridepublic void execute() {System.out.println("stargtegy1.execute...");}}package com.array7.strategy;public class Strategy2 implements IStrategy {@Overridepublic void execute() {System.out.println("stargtegy2.execute...");}}package com.array7.strategy;public class Strategy3 implements IStrategy {@Overridepublic 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();}}


0 0
原创粉丝点击