您的位置:首页 > 其它

一起学习设计模式-策略模式

2015-04-20 09:59 274 查看
大家好:

我近期写了一个TCP长连接的框架,封装的Netty,序列化采用的是PB,内存缓存用的Google的Guava。项目托管在GitHub上,开源希望大家能用起来并且一起维护这个项目。我是做游戏服务器的,像客户端的引擎框架有Cocos2d , Unity等。而服务器没有相对来说比较好的开源的架构(或者说鄙人学识浅薄没有发现)。我也经历了几个游戏从开发到上线的这样一个过程,所以也看到过几个比较优秀的框架,现在的想法是能够开源一个服务器框架,然后大家各抒己见共同维护这个框架。因为我的经验尚短,框架中难免有疏漏或者不稳妥之处,所以希望大牛能多提供意见。

GitHub地址:https://github.com/luzhiming/opentcpserver

设计模式之策略模式-可以让你随时更换不同的算法使用不同的策略完成相应的逻辑功能。

策略模式源代码:https://github.com/luzhiming/DesignPattern/tree/master/DesignPattern

策略模式讲解视频:(由于耳麦原因音质不是很好-如果朋友们哪里觉得听的不清楚的可以给我留言,我再重新录制或者给大家讲一遍也可以)http://pan.baidu.com/s/1dDGnYJB

策略模式中几个比较重要的角色

1.抽象策略角色(一个抽象类或者一个接口)

2.具体策略实现(实现抽象策略角色)

3.策略持有者

我的CSDN关于策略模式的例子:让你用不同的笔写字

今天再举一个例子:策略模式之高考

1.抽象策略角色-试卷

2.具体策略角色 - A卷 B卷 C卷 D卷

3.山东省,河北省,北京市

为什么使用策略模式呢?

这里使用策略模式就是为了可以随时更换不同的策略(试卷类型)。

1.抽象策略角色(试卷)

package com.luzm.stratagy;

public interface TestPaper {
/**
* 获取考试内容
* @return
*/
public String getTestContent();
}


2.具体策略 A B C D 卷

A卷

package com.luzm.stratagy;

public class TestPaperA implements TestPaper {

@Override
public String getTestContent() {
return "This is TestPaperA Content";
}

}


B卷

package com.luzm.stratagy;

public class TestPaperB implements TestPaper {

@Override
public String getTestContent() {
return "This is TestPaperB Content";
}

}


C卷

package com.luzm.stratagy;

public class TestPaperC implements TestPaper {

@Override
public String getTestContent() {
return "This is TestPaperC Content";
}

}


D卷

package com.luzm.stratagy;

public class TestPaperD implements TestPaper {

@Override
public String getTestContent() {
return "This is TestPaperD Content";
}

}


3.抽象持有者

package com.luzm.stratagy;

public abstract class TestCity {
private TestPaper testPaper;

public TestPaper getTestPaper() {
return testPaper;
}

public void setTestPaper(TestPaper testPaper) {
this.testPaper = testPaper;
}

public void printTestContent(){
if(testPaper == null) {
System.out.println("NULL - ERR");
return ;
}
System.out.println(testPaper.getTestContent());
}
}


4.具体持有者

山东

package com.luzm.stratagy;

public class Shandong extends TestCity{

}


河北

package com.luzm.stratagy;

public class HeBei extends TestCity{

}


北京

package com.luzm.stratagy;

public class Beijing extends TestCity{
}


5.使用范例

package com.luzm.stratagy;

public class Test {

public static void main(String[] args) {
TestCity tc = new Shandong();
tc.setTestPaper(new TestPaperA());
tc.setTestPaper(new TestPaperC());
tc.printTestContent();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: