前两版DoubanFm写的太戳,第一版可以忽略,当是熟悉WP手机的一些API。。

第二版用了比较多的依赖注入,熟悉了Messenger,过后越写越大,感觉不对,赶快打住。。现在开始好好思考各模块了。

在Http请求方面,在知道了Restful后还没有机会使用它,感觉Restful应该还不错,不过我还是为我的Http请求使用了下面的设计模式

一.工厂方法

1.抽象产品

UML有空再画,先上代码,

使用Rx建立抽象的Get类产品,如下:

 1 public  abstract class HttpGetMethodBase<T>
 2     {
 3             public virtual IObservable<T> Get(string Url)//设置虚拟方法是为了多态 但是这里不用设置应该也可以
 4             {
 5                 //多态既是为了用子类的方法
 6                 //其实我这里不需要用子类的方法
 7                 //写了应该也可以
 8                 //只要注意子类的Override
 9                 var func = Observable.FromAsyncPattern<HttpWebRequest, T>(Webrequest, WebResponse);
10                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
11                 return func(request);
12             }
13            private  IAsyncResult Webrequest(HttpWebRequest request, AsyncCallback callbcak, object ob)
14             {
15                 return request.BeginGetResponse(callbcak, request);
16             }
17
18            //发的请求用的是父类的get,WebResponse用的是子类的
19             protected    abstract T WebResponse(IAsyncResult result);
20      }

作为抽象的产品,有些方法可以共享,比如Get方法。要重写的是WebResponse

2.具体产品

(1)返回stream的产品

 1   public class HttpGetStream : HttpGetMethodBase<Stream>
 2     {
 3         protected override Stream WebResponse(IAsyncResult result)
 4         {
 5             try
 6             {
 7                 var request = result.AsyncState as HttpWebRequest;
 8                 HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
 9                 #region ignore
10                 if (response.Cookies != null)
11                 {
12                     foreach (Cookie cookie in response.Cookies)
13                     {
14                         Debug.WriteLine(cookie.Value);
15                     }
16                 }
17                 Debug.WriteLine(response.ContentType);
18                 Debug.WriteLine(response.StatusDescription);
19                 if (response.Headers["Set-Cookie"] != null)
20                 {
21                     //setting may write
22                     Debug.WriteLine(response.Headers["Set-Cookie"]);
23                 }
24                 #endregion
25                return  response.GetResponseStream();
26             }
27             catch
28             {
29                 Debug.WriteLine("WEBERROR");
30                 return null;
31             }
32         }
33     }

(2)返回string的产品

 1   public class HttpGetString : HttpGetMethodBase<string>
 2     {
 3         protected  override string WebResponse(IAsyncResult result)
 4         {
 5             try
 6             {
 7                 var request = result.AsyncState as HttpWebRequest;
 8                 HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
 9                 #region ignore
10                 if (response.Cookies != null)
11                 {
12                     foreach (Cookie cookie in response.Cookies)
13                     {
14                         Debug.WriteLine(cookie.Value);
15                     }
16                 }
17                 Debug.WriteLine(response.ContentType);
18                 Debug.WriteLine(response.StatusDescription);
19                 if (response.Headers["Set-Cookie"] != null)
20                 {
21                     //setting may write
22                     Debug.WriteLine(response.Headers["Set-Cookie"]);
23                 }
24                 #endregion
25                 Stream stream = response.GetResponseStream();
26                 using (StreamReader sr = new StreamReader(stream))
27                 {
28                     return sr.ReadToEnd();
29                 }
30             }
31             catch
32             {
33                 Debug.WriteLine("WEBERROR");
34                 return null;
35             }
36         }
37     }

(3)返回位图的产品

 1   public class HttpGetBitmapImage : HttpGetMethodBase<BitmapImage>
 2     {
 3         protected override BitmapImage  WebResponse(IAsyncResult result)
 4         {
 5             try
 6             {
 7                 var request = result.AsyncState as HttpWebRequest;
 8                 HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
 9                 #region ignore
10                 if (response.Cookies != null)
11                 {
12                     foreach (Cookie cookie in response.Cookies)
13                     {
14                         Debug.WriteLine(cookie.Value);
15                     }
16                 }
17                 Debug.WriteLine(response.ContentType);
18                 Debug.WriteLine(response.StatusDescription);
19                 if (response.Headers["Set-Cookie"] != null)
20                 {
21                     //setting may write
22                     Debug.WriteLine(response.Headers["Set-Cookie"]);
23                 }
24                 #endregion
25                 Stream stream = response.GetResponseStream();
26                 BitmapImage bitmapimage = new BitmapImage();
27                 bitmapimage.SetSource(stream);
28                 return bitmapimage;
29             }
30             catch
31             {
32                 Debug.WriteLine("WEBERROR");
33                 return null;
34             }
35         }
36     }

现在主要有三种产品,如果以后有返回音频的产品,就照搬就好了,这样便于扩展。

3.接口工厂(不叫抽象工厂是怕跟抽象工厂模式冲突)

(1)用于创建对象(产品)的接口

 interface IHttpGet<T>{HttpGetMethodBase<T> CreateHttpRequest();}

(2)具体的工厂

具体工厂都用来创建具体的产品

1.string(get)工厂

1  public class StringHttpFactory:IHttpGet<string>
2     {
3          public HttpGetMethodBase<string>  CreateHttpRequest()
4         {
5             return new HttpGetString();
6         }
7     }

2.stream(get)工厂

1   public class StreamHttpFactory : IHttpGet<Stream>
2     {
3
4         public HttpGetMethodBase<Stream> CreateHttpRequest()
5         {
6             return new HttpGetStream();
7         }
8     }

3.位图工厂

1 public class BitmapImageHttpFactory : IHttpGet<BitmapImage>
2     {
3         public HttpGetMethodBase<BitmapImage> CreateHttpRequest()
4         {
5             return new HttpGetBitmapImage();
6         }
7     }

客户端调用:

客户端调用还是得知道具体的工厂型号,所以这里我打个问号,先看看代码吧

1   IHttpGet<string> factory = new StringHttpFactory();//string 工厂
2             factory.CreateHttpRequest().Get("http://douban.fm/j/mine/playlist?from=mainsite&channel=0&kbps=128&type=n").Subscribe(
3                 (result) =>
4                 {
5                   7                 });

代码new了一个具体的工厂,这里并没有达到真正的解耦,所以我考虑看能不能以后做

1。配置文件反射处理

2.依赖注入。

//to be continued................

二.职责链

先看看背景。

虽然用Newtonsoft的json库很爽,但是面对复杂的json串,不能很好的面对它的变化,变化点在于,JToken[][][][][][][][][],中括号的个数未知,我不知道哪天出来的json串会有几个[],如果使用到解析json串的地方很多,这个中括号的数量会非常多,看着非常恶心。。。。。。。。当然也许Newtonsoft有解决办法,但是我没摸索出来。

1.Json串的多样性

json串是由Web服务端安排的,各种命名,各种key/vaule,客户端很难应对这种变。

用职责链的效果是:客户端只用发出获得的json字符串,就可以获得与之对应的类,至于json串怎么被处理的,客户端不知道

上代码

 1   public abstract class RequestorBase<T>
 2     {
 3         protected RequestorBase<T> Successor;
 4         internal void SetSucessor(RequestorBase<T> suc)
 5         {
 6             Successor = suc;
 7         }
 8         public abstract T ProcessRequest(string json);//抽象不依赖于具体,抽象依赖于抽象
 9     }

10     public class Requestor1<T> : RequestorBase<T>
11     {
12         public override T ProcessRequest(string json)
13         {
14             try
15             {
16                 return JsonConvert.DeserializeObject<T>(JToken.Parse(json)["song"].ToString());
17             }
18             catch
19             {
20                 Debug.WriteLine("这个是在职责链中的该有的异常");
21                 return Successor.ProcessRequest(json);
22             }
23         }
24     }
25     public class Requestor2<T> : RequestorBase<T>
26     {
27         public override T ProcessRequest(string json)
28         {
29             try
30             {
31                 return JsonConvert.DeserializeObject<T>(JToken.Parse(json)["song"][0].ToString());
32             }
33             catch
34             {
35                 Debug.WriteLine("这个是在职责链中的该有的异常");
36                 return Successor.ProcessRequest(json);
37             }
38         }
39     }
40     public class Requestor3<T> : RequestorBase<T>
41     {
42         public override T ProcessRequest(string json)
43         {
44             Debug.WriteLine("在职责链中没有能找到处理请求的方法,返回Default");
45             return default(T);
46             //NO Chain 继续下去了
47         }
48     }

不同的职责人作不同的json串解析。

然后再使用

三.单例模式

使用单例模式来创建管理职责链,使用单例管理职责链的目的是职责链只负责处理json串,他们都是无状态的,所有把他们的方法装入内存就可以了。

 1   public class ManagerResponsibilityChain<T>
 2     {
 3        static private RequestorBase<T> _startrequestor;
 4        static public RequestorBase<T> Instance_Startrequestor
 5         {
 6             get
 7             {
 8                 if (_startrequestor == null)
 9                 {
10                     Inital();
11                 }
12                 return _startrequestor;
13             }
14         }
15         private ManagerResponsibilityChain()
16         {
17
18         }
19         static private void Inital()
20         {
21             _startrequestor = new Requestor1<T>();
22             var secondrequestor = new Requestor2<T>();
23             var thridrequestor = new Requestor3<T>();
24             _startrequestor.SetSucessor(secondrequestor);
25             secondrequestor.SetSucessor(thridrequestor);//requestor3 is the end
26         }
27     }

今天就到这。

后面再来追加一下:

对于上面的职责链,要想增加职责者,难免会忘记增加的过程,要插入在倒数第二个地方,再重新设置后两个的职责链

 1    public class ManagerResponsibilityChain<T>
 2     {
 3         static private RequestorBase<T> _startrequestor;
 4         static public RequestorBase<T> Instance_Startrequestor
 5         {
 6             get
 7             {
 8                 if (_startrequestor == null)
 9                 {
10                     Inital();
11                 }
12                 return _startrequestor;
13             }
14         }
15         private ManagerResponsibilityChain()
16         {
17
18         }
19         static public List<RequestorBase<T>> RequestList=new List<RequestorBase<T>>();
20         static private void InsertARequestor(RequestorBase<T> InsertItem)
21         {
22             RequestList.Insert(RequestList.Count - 1, InsertItem);
23             InsertItem.SetSucessor(RequestList[RequestList.Count - 1]);
24             RequestList[RequestList.Count - 3].SetSucessor(InsertItem);
25
26         }
27
28
29         static private void Inital()
30         {
31
32             _startrequestor = new Requestor1<T>();
33             var secondrequestor = new Requestor2<T>();
34             var thridrequestor = new Requestor3<T>();
35             RequestList.Add(_startrequestor);
36             RequestList.Add(secondrequestor);
37             RequestList.Add(thridrequestor);
38             _startrequestor.SetSucessor(secondrequestor);
39             secondrequestor.SetSucessor(thridrequestor);//requestor3 is the end
40
41
42             InsertARequestor(new Requestor4<T>());
43             InsertARequestor(new Requestor5<T>());
44             InsertARequestor(new Requestor6<T>());
45         }
46
47     }

或者是

 1   public class ManagerResponsibilityChain<T>
 2     {
 3         static private RequestorBase<T> _startrequestor;
 4         static public RequestorBase<T> Instance_Startrequestor
 5         {
 6             get
 7             {
 8                 if (_startrequestor == null)
 9                 {
10                     Inital();
11                 }
12                 return _startrequestor;
13             }
14         }
15         private ManagerResponsibilityChain()
16         {
17
18         }
19
20       static  private void InsertARequestor(RequestorBase<T> InsertItem, List<RequestorBase<T>> RequestList)
21         {
22             RequestList.Insert(RequestList.Count - 1, InsertItem);
23             InsertItem.SetSucessor(RequestList[RequestList.Count - 1]);
24             RequestList[RequestList.Count - 3].SetSucessor(InsertItem);
25
26         }
27
28
29         static private void Inital()
30         {
31             List<RequestorBase<T>> RequestList = new List<RequestorBase<T>>();
32             _startrequestor = new Requestor1<T>();
33             var secondrequestor = new Requestor2<T>();
34             var thridrequestor = new Requestor3<T>();
35             RequestList.Add(_startrequestor);
36             RequestList.Add(secondrequestor);
37             RequestList.Add(thridrequestor);
38             _startrequestor.SetSucessor(secondrequestor);
39             secondrequestor.SetSucessor(thridrequestor);//requestor3 is the end
40
41
42             InsertARequestor(new Requestor4<T>(), RequestList);
43             InsertARequestor(new Requestor5<T>(), RequestList);
44             InsertARequestor(new Requestor6<T>(), RequestList);
45         }
46
47     }

转载于:https://www.cnblogs.com/07lyt/p/3991614.html

DoubanFm之设计模式(一)相关推荐

  1. 【Design pattern】设计模式思路总结(一)

    看了一周的设计模式,跟着小菜的思路走! 从简单工厂过渡策略,后面看的这几个模式都是在单一职责,开放--封闭原则,依赖倒转原则下不断的改进,采用模式写出的代码更容易扩展,维护! 比较容易懂. 装饰模式: ...

  2. GOF23设计模式(结构型模式)代理模式~

    代理模式应用场景十分广泛,随便一个框架都会用到,因此学好代理模式对后续框架学习是最基本的要素!!今天我们就来讲讲代理模式! 目录 1.简介 1. 核心作用 2. 角色分析 2. 应用场景 4. 分类 ...

  3. GOF23设计模式(创建型模式)工厂模式

    目录: 一:工厂模式的核心本质 二:关于面向对象的六大基本原则 三:工厂模式的三大类详解(代码示例,详细分析) 首先,上咱本GOF23所有工厂模式的分类表格!!! 创建型模式 单例模式.工厂模式.抽象 ...

  4. GOF23设计模式(创建型模式)单例模式

    目录: 一:单例模式的核心作用.常见应用场景 二:五种单例模式及其实现 三:关于反射和反序列化破解单例模式的漏洞,以及相应的解决方案 四:测试五种单例模式的效率 一:核心作用及常见应用场景: 核心作用 ...

  5. Python七大原则,24种设计模式

    七大设计原则: 1.单一职责原则[SINGLE RESPONSIBILITY PRINCIPLE]:一个类负责一项职责.  2.里氏替换原则[LISKOV SUBSTITUTION PRINCIPLE ...

  6. Java设计模式:单例模式

    学而时习,稳固而之心, 好久没有复习java的知识了,今天有空温习了单例模式,这里记录一下 单例模式是常见的设计模式的一种,其特点就是 指一个类只有一个实例,且该类能自行创建这个实例  , 保证一个类 ...

  7. 设计模式中的六大基本原则

    软件设计中的基本共识: 1,高内聚,低耦合:如果想使软件系统架构稳定,那么我们期望软件的各模块内元素结合的紧密,而模块之间的耦合度(关联性)越低越好.高内聚不仅体现在模块上,单独的类或方法也应该是内聚 ...

  8. JS中的7种设计模式

    第九章Refactoring to OOP Patterns 重构为OOP模式 7种设计模式: 1,模版方法模式(template method) 2,策略模式(strategy) 3,状态模式(st ...

  9. 设计模式之创建型汇总

    设计模式 创建型 工厂方法模式 定义:定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类,工厂方法让类的实例化推迟到子类中进行 使用场景: 创建对象需要大量重复的代码 客户端(应用层)不依 ...

最新文章

  1. 下一代防火墙的5个优点
  2. 递归与递推 普通排队问题及带约束条件的排队问题 c代码
  3. hdu 1692(枚举+剪枝)
  4. MSP432P401R TI Drivers 库函数学习笔记(六)UART 串口
  5. 增加表单的文字段的html的代码是,表单及表单新增元素(示例代码)
  6. Gartner 发布2019年超融合魔力象限:新增深信服一员!
  7. “.NET研究”谈谈C# 4.0新特性“缺省参数”的实现
  8. 防止ACCESS数据库被下载的9种方法
  9. jQuery mobile button 禁用和启用
  10. 【前端 · 面试 】JavaScript 之你不一定会的基础题(二)
  11. Python1 关于安装
  12. iphone163邮件服务器设置,怎样在iphone上设置网易免费企业邮箱收发邮件
  13. 手机12306买卧铺下铺技巧_12306网购火车票怎么选上中下铺(详细代码及图解)...
  14. 3dmax:3dmax的软件中右边工具栏的创建、修改、层次、运动、显示、几何体的粒子系统、工具、灯光、摄影、空间扭曲、系统、实用程序、辅助对象等使用技巧之详细攻略
  15. 高效能人士的七个习惯——由内而外全面造就自己
  16. 使用Robot Framework做接口测试
  17. Ble低功耗蓝牙和蓝牙mesh网络之间的关系
  18. java for 字母金字塔_扣丁学堂Java培训简述如何用C#随机数生成字母金字塔
  19. Sulley fuzzer learning
  20. 关于Ubuntu18.04 Cisco AnyConnect闪退的问题

热门文章

  1. Unirech腾讯云国际版-使用腾讯云服务器手动建立WordPress 个人站点Linux系统教程
  2. quoted-printable解码程序
  3. Verilog之闪烁灯
  4. 1.7.3_NandFlash的芯片id读取_P
  5. 如何在 Python3 中对列表 通过比较排序(不懂就问)?
  6. 计算机网络拓扑图的描述,计算机网络拓扑结构 以下关于星型网络拓扑结构的描述正确的是______。 (多选题 )...
  7. Unity2021 Inventory(背包)系统学习记录
  8. ubuntu 或者虚拟机连接u盘
  9. TheTechBehindDx11UnrealEngineSamaritanDemo
  10. python loc和iloc_DataFrame的iloc与loc的区别是什么?