C#设计模式/Command模式

原型

 1 public   class  log
 2 {
 3  public void Write(string target,string log)
 4  {
 5    //实现内容
          Console.WriteLine("Logging {0} to file {1}.",log,target);
 6  }

 7}

 8
 9 log log = new  log()
10  log.Write( " error.log " , " log " );

封装变化-封装用户请求的变化(需改变Write()方法)
C#设计模式/Command模式_第1张图片

 

public   interface  ILogWriter
    
{
        
void Write(string target,string logValue);
    }

public   class  DBLogWriter:ILogWriter
    
{
        
ILogWriter Members#region ILogWriter Members

        
public void Write(string target, string logValue)
        
{
            Console.WriteLine(
"Logging {0} to DB {1}.", logValue, target);            
        }


        
#endregion
        
    }

public   class  TxtLogWriter:ILogWriter
    
{
        
ILogWriter Members#region ILogWriter Members

        
public void Write(string target, string logValue)
        
{
            Console.WriteLine(
"Logging {0} to text file {1}.",logValue,target);            
        }


        
#endregion

    }

 
public   class  XmlLogWriter:ILogWriter
    
{
        
ILogWriter Members#region ILogWriter Members

        
public void Write(string target, string logValue)
        
{
            Console.WriteLine(
"Logging {0} to xml file {1}.", logValue, target);            
        }


        
#endregion

    }
   
public   class  Log
    
{
        
private ILogWriter m_log;
        
public Log(ILogWriter log)
        
{
            m_log 
= log;
        }

        
public void Write(string target, string logValue)
        
{
            m_log.Write(target,logValue);
        }

    }
    
class  Program
    
{
        
static void Main(string[] args)
        
{
            Log lg
=new Log(new DBLogWriter());
            lg.Write(
"DBLogWriter","DBLogValue");
            Log lg1 
= new Log(new XmlLogWriter());
            lg1.Write(
"XmlLogWriter""XmlLogValue");
            Log lg2 
= new Log(new TxtLogWriter());
            lg2.Write(
"TxtLogWriter""TxtLogValue");
            Console.ReadLine();
        }

    }

转载于:https://www.cnblogs.com/el-net/articles/1108786.html

你可能感兴趣的:(C#设计模式/Command模式)