空对象模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NullObjectPattern
{
    public interface INullable
    {
        bool IsNull { get; }
    }
    public interface IUser : INullable
    {
        void Login();
        void GetInfo();
    }
    public class User : IUser
    {
        public void Login()
        {
            Console.WriteLine("User Login now.");
        }
        public void GetInfo() 
        {
            Console.WriteLine("User Logout now.");    
        }
        public bool IsNull
        {
            get { return false; }
        }
    }
    public class NullUser : IUser
    {
        public void Login()
        {
            
        }
        public void GetInfo()
        {
            
        }
        public bool IsNull
        {
            get { return true; }
        }
    }
    public class UserManage
    {
        private IUser user = new User();
        public IUser User
        {
            get { return user; }
            set { user = value ?? new NullUser(); }
        }
    }
    
    class Client
    {
        static void Main(string[] args)
        {
            UserManage manager = new UserManage();
            //manager.User = new User();
            manager.User = null;
            manager.User.Login();
            manager.User.GetInfo();
            if (manager.User.IsNull)
            {
                Console.WriteLine("User isn't exist,Please Cheack it!");
            }
        }
    }
}
/**************** Summary *****************************/
//1.valid solves the state of when object is Nullable.
//2.ensured can return a valid default value.
//example:
    //public void SendMessageAll(List<User> userList)
    //{
    //    foreach(User user in userList)
    //    {
    //        user.SendMessage();
    //    }
    //}
//3.Supply unified judge the Property of IsNull,by Implement INullable or Extension Method.
//4.null Object Should be keep the invariability of the Object's Members,so we Implement Singleton Pattern generally.
//5.when the executed the method,return "null object" and non "null",can avoid NullReferenceException.
posted @ 2011-03-24 22:31  山之松  阅读(369)  评论(0编辑  收藏  举报