2014-06-06 5 views
-3

인터페이스를 통해 아래의 클래스 메서드를 노출하는 데 도움이 될 수 있습니까? 인터페이스를 통해 아래의 Cache 클래스 메소드를 사용할 수 있기를 원합니다. 기본적으로 공통 캐시 메소드가 정의 된 일반 인터페이스를 생성해야하며 해당 구현은 아래 클래스에서 제공됩니다.일반 인터페이스 구현

public class CacheStore 
{ 
    private Dictionary<string, object> _cache; 
    private object _sync; 

    public CacheStore() 
    { 
     _cache = new Dictionary<string, object>(); 
     _sync = new object(); 
    } 

    public bool Exists<T>(string key) where T : class 
    { 
     Type type = typeof(T); 

     lock (_sync) 
     { 
      return _cache.ContainsKey(type.Name + key); 
     } 
    } 

    public bool Exists<T>() where T : class 
    { 
     Type type = typeof(T); 

     lock (_sync) 
     { 
      return _cache.ContainsKey(type.Name); 
     } 
    } 

    public T Get<T>(string key) where T : class 
    { 
     Type type = typeof(T); 

     lock (_sync) 
     { 
      if (_cache.ContainsKey(key + type.Name) == false) 
       throw new ApplicationException(String.Format("An object with key '{0}' does not exists", key)); 

      lock (_sync) 
      { 
       return (T)_cache[key + type.Name]; 
      } 
     } 
    } 

    public void Add<T>(string key, T value) 
    { 
     Type type = typeof(T); 

     if (value.GetType() != type) 
      throw new ApplicationException(String.Format("The type of value passed to 
      cache {0} does not match the cache type {1} for key {2}",  
      value.GetType().FullName, type.FullName, key)); 

     lock (_sync) 
     { 
      if (_cache.ContainsKey(key + type.Name)) 
       throw new ApplicationException(String.Format("An object with key '{0}' 
       already exists", key)); 

      lock (_sync) 
      { 
       _cache.Add(key + type.Name, value); 
      } 
     } 
    } 
} 
+0

어떤 인터페이스입니까? 당신이 묻고있는 것이 명확하지 않습니다. –

+1

메소드 서명을 인터페이스로 추출하고'public'을 제거하고 인터페이스에 이름을 지정하면 완료됩니다. –

답변

3

다음과 같이 인터페이스를 쉽게 추출 할 수 있습니다.

interface ICache 
{ 
    bool Exists<T>(string key) where T : class; 
    bool Exists<T>() where T : class; 
    T Get<T>(string key) where T : class; 
    void Add<T>(string key, T value); 
} 

이제는 class CacheStore : ICache을 수행하여 클래스를 구현할 수 있습니다.


는 제외 : 오히려 키와 형식 이름의 문자열 연결을 사용하는 것보다, 당신은 단순히 당신의 Dictionary 키의 형태를 만들 수있는 Tuple<Type, string> :

private Dictionary<Tuple<Type, string>, object> _cache; 

그것은, 여기 당신이 구현할 수있는 방법은 명확하게하려면 이 변화에 처음 Exists 방법 :

public bool Exists<T>(string key) where T : class 
{ 
    Type type = typeof(T); 

    lock (_sync) 
    { 
     return _cache.ContainsKey(Tuple.Create(type, key)); 
    } 
} 

이 조금 깨끗하고 모든 장점이됩니다 이름 충돌에 대해 걱정할 필요가 없기 때문입니다. 현재 설정에서 Location 키를 "FriendGeo", GeoLocation 키를 "Friend"으로 추가하면 어떻게됩니까? 둘 다 연결하여 동일한 문자열 "FriendGeoLocation"을 형성합니다. 이것은 고의적으로 보일지 모르지만, 만약 그것이 끝나면 디버깅하기가 매우 어리석은 (그리고 잘못된) 행동을하게 될 것입니다.

0

Visual Studio에서 자동으로이 작업을 수행 할 수있는 도구가 있습니다. 클래스를 마우스 오른쪽 버튼으로 클릭하고 Refactor, Extract Interface, Select All, Ok를 선택합니다.

관련 문제