日期:2014-05-20  浏览次数:20807 次

装饰器模式的问题
我有一个抽象类
abstract class Log
{
    public string message;
    abstract public void Write();
}
和一个实体类
class TextLog : Log
{
    public override void Write()
    {
        Console.WriteLine(message);
    }
}
我想编写两个装饰类PriorityLog和ErrorLog,能够对一个Log进行装饰,
能够实现如下结果
TextLog log=new TextLog();
t.message="删除用户";
t.Write();
打印结果为:删除用户

PriorityLog plog=new Priority(log);
plog.level=1;
plog.Write();
打印结果为:删除用户,优先级别:1

ErrorLog elog=new ErrorLog(plog);
elog.level=2;
elog.Write();
打印结果为:删除用户,优先级别:1,错误级别:2

用装饰器模式如何实现?请高手指教!!

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TextLog log = new TextLog();
            log.message = "删除用户";
            log.Write();

            PriorityLog plog = new PriorityLog(log);
            plog.level = 1;
            plog.Write();

            ErrorLog elog = new ErrorLog(plog);
            elog.level = 2;
            elog.Write();

            Console.ReadKey();
        }
    }


    abstract class Log
    {
        public string message;
        abstract public void Write();
    }
    class TextLog : Log
    {
        public override void Write()
        {
            Console.WriteLine();
            Console.Write(message);
        }
    }

    class PriorityLog : Log
    {
        Log _log;
        public int? level;

        public PriorityLog(Log log)
        {
            _log = log;
        }