talk is cheap show me the code
享元模式
- 享元模式
interface FlyWeight{
void doA(String name);
}
//享元模式即为保证对象创建过多找出内存溢出等问题,实现一个可分享共用对象
class FlyWeightObj implements FlyWeight{
void doA(String name){
system.out.println("this is Fobj")
}
}
//共享数据
class FlyWeightFactory{
public static ConcurrentHashMap<String, FlyWeight> allFlyWeight = new ConcurrentHashMap<String, FlyWeight>();
public static FlyWeight getFlyWeight(Stirng name){
if(null == allFlyWeight.get(name)){
synchronized(allFlyWeight ){
if(null == allFlyWeight.get(name)){
FlyWeight f = new FlyWeightObj ();
allFlyWeight .add(name,f);
}
}
return allFlyWeight .get(name);
}
}
}
责任链模式
- 责任链模式Filter
interface Filter{
void doFilter(Request req,Response rep,ChainFilter cf);
}
class FilterA implements Filter{
void doFilter(Request req,Response rep,ChainFilter cf){
//do AnyTHING
cf.doFilter(req,rep,cf);
}
}
class FilterB implements Filter{
void doFilter(Request req,Response rep,ChainFilter cf){
//do AnyTHING
cf.doFilter(req,rep,cf);
}
}
//将Filter 加入链
class ChainFilter inplements Filter{
//责任链
List<Filter> filters = new ArrayList<>();
//filter引用顺序
private int index = 0;
public ChainFilter addFilter(Filter f ){
filters.add(f);
return this;
}
public void doFilter(Request req,Response rep,ChainFilter cf){
if(index = filters.size())
return;
Filter f = filters.get(index);
index++;
f.doFilter(req,rep,cf);
}
}
//测试类
class Test{
public static void main(String[] args){
Filter fa = new FilterA();
Filter fb = new FilterB();
ChainFilter chain = new ChainFilter();
chain.addFilter(fa);
chain.addFilter(fa);
chain.doFilter(new Fequest(),new Response,chain);
}
}
命令模式
- 命令模式 遥控
//命令接口
interface Command{
void doCommand();
}
//电视接口
class Tv{
public void doOn(){
}
public void doOff(){
}
public void doChange(){
}
}
//按钮
class ChangeTv implements Command{
private Tv tv ;
pulic ChangeTv (Tv tv){
this.tv = tv;
}
void doCommand(){
tv.doChange();
}
}
//按钮
class OffTv implements Command{
private Tv tv ;
pulic Offtv(Tv tv){
this.tv = tv;
}
void doCommand(){
tv.doOff();
}
}
//按钮
class OnTv implements Command{
private Tv tv ;
pulic Ontv(Tv tv){
this.tv = tv;
}
void doCommand(){
tv.doOn();
}
}
//遥控
class Controller{
private ChangeTv ctv, OnTv otv,OffTv offtv;
public Controller( ChangeTv ctv, OnTv otv,OffTv offtv){
this.ctv = ctv;
this.otv = otv;
this.offtv = offtv;
}
public void doOn(){
otv.doCommand();
}
public void doOff(){
offtv.doCommand();
}
public void doChange(){
ctv.doCommand();
}
}
//测试
class Test{
public static void main(String[] args){
Tv tv = new Tv();
.......
Controller ct = new Controller(ctv, otv, offtv)
ct.doChange();
ct.doOff();
}
}
网友评论