设计思考之“IComponent-ISite-IContainer 组合还是继承,这是个问题”

要从framework里面的几个接口说起。在System.ComponentModel中定义有这样两个接口:IComponent(组件)和IContainer(容器)。两者都很简单,关系也很简单,就是组件可以放在容器里
    IContainer.Add(:IComponent)
为了维护这种关系,定义了第三个接口:ISite(站点?)。ISite是一个简单的关联接口,连接了IComponentIContainer,添加和移出组件(IContainer的Add和Remove)的实现,就是通过维护一个数组ISite[]来完成。如此,构成了IComponent-ISite-IContainer这样的模式。
 
问题是,为什么IComponent不设计为一个多重接口继承,即:
    public interface IComponent : IDisposable, ISite
    
{
    }
而是采用了组合一个ISite接口的方式:
    public interface IComponent : IDisposable
    
{
        ISite Site 
getset; }
    }
 
这样,在具体实现IComponent的Component类中,凭空多了一项简单传递的工作:
    public class Component : MarshalByRefObject, IComponent {
        
public IContainer Container {
            
get {
                ISite s 
= site;
                
return s == null? null : s.Container;
            }

        }


        
protected virtual object GetService(Type service) {
            ISite s 
= site;
            
return((s== null? null : s.GetService(service));
        }


        
protected bool DesignMode {
            
get {
                ISite s 
= site;
                
return(s == null? false : s.DesignMode;
            }

        }

    }
显然,如果IComponent采用的是继承的话,就不必多这么一个“传递层”。单从实现层面讲,好像完全可以采用继承,并且稍微比较方便。
 
思考了一下,得出如下可能的设计考量:
  1. IComponent has a ISite而不是IComponet is a ISite
  2. ISite专职专责,符合单一职责原则,虽然它职责很简单
  3. 想好了再补充...

欢迎大家批评、指正、补充

 

posted on 2004-12-15 15:04  Avant  阅读(2206)  评论(4编辑  收藏  举报

导航