📄 client.java
字号:
/*
* Created on 2005-5-11
*
意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
适用性 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[ H O 8 7 ] ,可以使用策略模式。
算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
一个类定义了多种行为, 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的S t r a t e g y 类中以代替这些条件语句。
*/
package com.test.pattern.behavir.strategy;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
abstract class Strategy {
abstract public void DoAlgorithm();
}
class FirstStrategy extends Strategy {
public void DoAlgorithm() {
System.out.println("In first strategy");
}
}
class SecondStrategy extends Strategy {
public void DoAlgorithm() {
System.out.println("In second strategy");
}
}
class Context {
Strategy s;
public Context(Strategy strat) {
s = strat;
}
public void DoWork() {
// some of the context's own code goes here
}
public void DoStrategyWork() {
// now we can hand off to the strategy to do some
// more work
s.DoAlgorithm();
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client {
public static void main(String[] args) {
FirstStrategy firstStrategy = new FirstStrategy();
Context c = new Context(firstStrategy);
c.DoWork();
c.DoStrategyWork();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -