C#中类和接口的设计思想(本人认为比较好的思想,欢迎大家讨论指点)

        当我们设计一个类时,首先要规划这个类主要是干什么用的,并且对外要放出哪些接口。这时就要设计这个类的对外接口都有哪些了。在进行多层次开发的时候,由于下层对上层是透明的,上层无须知道下层的操作方式以及代码,因此我主张层与层之间的交互主要靠的是接口。尽量不要用类。下面的代码是设计的接口,类,以及其他的层的调用。


 

 1    public interface IMaster
 2    {
 3        /// <summary>
 4        /// 获得名称
 5        /// </summary>

 6        string GetName();
 7        /// <summary>
 8        /// 设置名称
 9        /// </summary>
10        /// <param name="str">名称</param>

11        void SetName(string str);
12    }

13    public class Master:IMaster
14    {
15        /// <summary>
16        /// 底层
17        /// </summary>

18        private Master()
19        {
20            //
21            // TODO: 在此处添加构造函数逻辑
22            //
23        }

24        private static Master _instance = null;
25        /// <summary>
26        /// 
27        /// </summary>
28        /// <returns></returns>

29        public static Master Instance()
30        {
31            if(_instance == null)
32            {
33                _instance =  new Master();
34            }

35            return _instance;
36        }

37        private string Name;
38
39        IMaster接口
51    }

52
53    /// <summary>
54    /// 上层
55    /// </summary>

56    public class User
57    {
58        IMaster MasterExample = null;
59        public User()
60        {
61            MasterExample = Master.Instance();
62        }

63        
64        public string GetUseName()
65        {
66            return MasterExample.GetName();
67        }

68        public string SetUseName(string str)
69        {
70            MasterExample.SetName(str);
71        }

72    }
posted @ 2006-04-18 14:53  李阳  阅读(2327)  评论(17编辑  收藏  举报