close

This tutorial is about proxy pattern, which is my thoghts after watching the tutorial created by Christopher Okhravi.

  1. Virtual Proxy

  2. Remote Proxy

  3. Protection Proxy

image

 Virtual Proxy:

image

IBookParser portion:

   1: interface IBookParser
   2: {
   3:     int getNumPages();
   4: }

BookParser portion:

   1: class BookParser : IBookParser
   2: {
   3:     string book;
   4:     public BookParser(String _book)
   5:     {
   6:         this.book = _book;
   7:     }
   8:  
   9:     public int getNumPages()
  10:     {
  11:         return Convert.ToInt32(book);
  12:     }
  13: }

LazyBookParser portion:

   1: class LazyBookParser : IBookParser
   2: {
   3:     private IBookParser parser = null;
   4:     private string book;
   5:     public LazyBookParser(string _book)
   6:     {
   7:         this.book = _book;
   8:     }
   9:    
  10:     public int getNumPages()
  11:     {
  12:         if (this.parser == null)
  13:             parser = new BookParser(this.book);
  14:         return this.parser.getNumPages();            
  15:     }
  16: }

Console portion:

   1: static void Main(string[] args)
   2: {
   3:    string book = "1234";
   4:    LazyBookParser lazyBookParser = new LazyBookParser(book);
   5:    Console.WriteLine("{0}",lazyBookParser.getNumPages());
   6:    Console.ReadKey();
   7: }

image

Remote Proxy

Now we are going to introduce an application of proxy pattern, which has two parts: client and server portions.

image

IActualPrices portion

   1: namespace ActualPriceLib
   2: {
   3:     public interface IActualPrices
   4:     {
   5:         string GoldPrice { get; }
   6:         string SilverPrice { get; }
   7:         string DollarToRupee { get; }
   8:     }
   9: }

TCPClient Project

image

IClient portion:

It is an interface that describes a client side must have following methods, including

Connect to server, Close connection, Disconnect to server, send a message, and receive response from server.

   1: public interface IClient
   2: {
   3:    void Connect();
   4:    void Close();
   5:    void Disconnect();
   6:    void SendMessage(string cmd);
   7:    string ReceiveData();
   8: }

IClient portion:

Then Client class implements all methods of IClient as follows

   1: public class Client : IClient
   2: {
   3:    bool bConnected = false;
   4:    TcpClient client = null;
   5:    string ipAddress = "127.0.0.1";
   6:    int nPort = 9999;
   7:    string response = string.Empty;
   8:    public Client(string _ipAddress, int _nPort)
   9:    {
  10:        this.ipAddress = _ipAddress;
  11:        this.nPort = _nPort;
  12:    }
  13:  
  14:    public void Connect()
  15:    { 
  16:        if (client == null) client = new TcpClient();      
  17:        while (!client.Connected)
  18:        {
  19:            try
  20:            {
  21:                client.Connect(ipAddress, nPort);
  22:            }
  23:            catch(Exception ex)
  24:            {
  25:                Console.WriteLine("server connection failed");
  26:            }
  27:        }
  28:  
  29:         //while (!client.Connected)
  30:         bConnected = client.Connected;
  31:    }
  32:    public void Close()
  33:    {
  34:        if (client.Connected) client.Close();
  35:    }
  36:    public void Disconnect()
  37:    {
  38:        if(client!=null)   client.Dispose();
  39:        client = null;
  40:    }
  41:    public string ReceiveData()
  42:    {
  43:        string result = string.Empty;
  44:        Stream stream = client.GetStream();
  45:      
  46:        const int len = 100;
  47:        byte[] br = new byte[len];
  48:        int k = stream.Read(br, 0, len);
  49:     
  50:        for (int i = 0; i < k; i++)
  51:        {
  52:            result += Convert.ToChar(br[i]);
  53:        }
  54:        Close();
  55:        Disconnect();
  56:        return result;
  57:    }
  58:    public void SendMessage(string cmd)
  59:    {
  60:        if (!bConnected) Connect();
  61:        Stream stream = client.GetStream();
  62:  
  63:  
  64:  
  65:        ASCIIEncoding asen = new ASCIIEncoding();
  66:        byte[] ba = asen.GetBytes(cmd.ToCharArray());
  67:        stream.Write(ba, 0, ba.Length);
  68:  
  69:    }
  70: }

In order to provide another way to send message from client to server, we build a static class named ClientFactory.

ClientFactory portion:

   1: public static class ClientFactory
   2: {
   3:    public static Client client = null;
   4:    public static string SendMessage(string input)
   5:    {
   6:        client = CreateClient();
   7:        client.Connect();
   8:        client.SendMessage(input);           
   9:        return client.ReceiveData();
  10:    }
  11:    private static Client CreateClient()
  12:    {
  13:        if (client == null) client = new Client("127.0.0.1", 9999);
  14:        return client;
  15:    }
  16: }

Now we are going to introduce ClientActualPrices class, which inherits IActualPrices

ClientActualPrices portion:

   1: using TCPClient;
   2: namespace ActualPriceLib
   3: {
   4:     class ClientActualPrices : IActualPrices
   5:     {
   6:         public string GoldPrice
   7:         {
   8:             get
   9:             {
  10:                 return ClientFactory.SendMessage("g");
  11:             }
  12:         }
  13:         public string SilverPrice
  14:         {
  15:             get
  16:             {
  17:                 return ClientFactory.SendMessage("s");
  18:             }
  19:         }
  20:         public string DollarToRupee
  21:         {
  22:             get
  23:             {
  24:                 return ClientFactory.SendMessage("d");
  25:             }
  26:         }
  27:     }
  28: }

ClientActualPricesProxy portion:

   1: public class ClientActualPricesProxy : IActualPrices
   2: {
   3:     ClientActualPrices actualPrices = new ClientActualPrices();
   4:  
   5:     public string GoldPrice
   6:     {
   7:         get
   8:         {
   9:             return actualPrices.GoldPrice;
  10:         }
  11:     }
  12:  
  13:     public string SilverPrice
  14:     {
  15:         get
  16:         {
  17:             return actualPrices.SilverPrice;
  18:         }
  19:     }
  20:  
  21:     public string DollarToRupee
  22:     {
  23:         get
  24:         {
  25:             return actualPrices.DollarToRupee;
  26:         }
  27:     }
  28: }

ClientConsole portion:

   1: static void Main(string[] args)
   2: {
   3:     IActualPrices proxy = new ClientActualPricesProxy();
   4:  
   5:     Console.WriteLine("Gold Price: {0} ", proxy.GoldPrice);
   6:     Console.WriteLine("Silver Price: {0}", proxy.SilverPrice);
   7:     Console.WriteLine("Dollar to Ruppe Conversion: {0}", proxy.DollarToRupee);
   8:  
   9:  
  10:     Console.ReadKey();
  11: }

image

IServer portion:

   1: public interface IServer
   2: {
   3:    void Start();
   4: }

ServerActualPrices portion:

   1: public class ServerActualPrices : IActualPrices
   2: {
   3:    public string GoldPrice
   4:    {
   5:        get
   6:        {
   7:            // This value should come from a DB typically
   8:            return "100";
   9:        }
  10:    }
  11:  
  12:    public string SilverPrice
  13:    {
  14:        get
  15:        {
  16:            // This value should come from a DB typically
  17:            return "5";
  18:        }
  19:    }
  20:  
  21:    public string DollarToRupee
  22:    {
  23:        get
  24:        {
  25:            // This value should come from a DB typically
  26:            return "50";
  27:        }
  28:    }
  29: }

ServerActualPricesProxy portion:

   1: public class ServerActualPricesProxy:IActualPrices
   2: {
   3:     ServerActualPrices serverActualPrices = new ServerActualPrices();
   4:  
   5:     public string GoldPrice
   6:     {
   7:         get
   8:         {
   9:             return serverActualPrices.GoldPrice;
  10:         }
  11:     }
  12:  
  13:     public string SilverPrice
  14:     {
  15:         get
  16:         {
  17:             return serverActualPrices.SilverPrice;
  18:         }
  19:     }
  20:  
  21:     public string DollarToRupee
  22:     {
  23:         get
  24:         {
  25:             return serverActualPrices.DollarToRupee;
  26:         }
  27:     }
  28: }

Server portion:

   1: public class Server:IServer
   2: {
   3:     TcpListener listener = null;
   4:     string ipAddress = "127.0.0.1";
   5:     int nPort = 9999;
   6:     Dictionary<string, string> actualPrices = new Dictionary<string, string>();
   7:     Dictionary<string, string> actualPricesInfo = new Dictionary<string, string>();
   8:     public Server(string _ipAddress, int _nPort)
   9:     {
  10:         this.ipAddress = _ipAddress;
  11:         this.nPort = _nPort;
  12:     }
  13:     private void InitPrices()
  14:     {
  15:         if(actualPrices.Count == 0)
  16:         {
  17:             IActualPrices proxy = new ServerActualPricesProxy();
  18:             actualPrices.Add("g", proxy.GoldPrice);
  19:             actualPrices.Add("s", proxy.SilverPrice);
  20:             actualPrices.Add("d", proxy.DollarToRupee);
  21:         }
  22:         if(actualPricesInfo.Count == 0)
  23:         {
  24:             actualPricesInfo.Add("g", "Gold Prices");
  25:             actualPricesInfo.Add("s", "Silver Price");
  26:             actualPricesInfo.Add("d", "Dollar To Rupee Prices");
  27:         }
  28:     }
  29:     public void Start()
  30:     {
  31:         InitPrices();
  32:         IPAddress ip = IPAddress.Parse(this.ipAddress);
  33:         this.listener = new TcpListener(ip, this.nPort);
  34:         while (true)
  35:         {
  36:             listener.Start();
  37:             Console.WriteLine("Waiting .....");
  38:             Socket s = listener.AcceptSocket();
  39:  
  40:             byte[] b = new byte[100];
  41:  
  42:             int count = s.Receive(b);
  43:  
  44:             string input = string.Empty;
  45:  
  46:             for (int i = 0; i < count; i++)
  47:             {
  48:                 input += Convert.ToChar(b[i]);
  49:             }
  50:            
  51:             string returnValue = string.Empty;
  52:             string message = string.Empty;
  53:             returnValue = actualPrices[input];
  54:             
  55:             ASCIIEncoding asen = new ASCIIEncoding();
  56:             s.Send(asen.GetBytes(returnValue));
  57:  
  58:             s.Close();
  59:             listener.Stop();
  60:             Console.WriteLine("Response for ({0}) Sent .....", actualPricesInfo[input]);
  61:         }
  62:     }
  63: }

Console portion:

   1: static void Main(string[] args)
   2: {
   3:    ServerFactory.CreateServer().Start();
   4:  
   5: }

 

image

 

 

References:

1. Understanding and Implementing Proxy Pattern in C#

2. Proxy Pattern – Design Patterns (ep 10)

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()