2012-04-19 6 views
8

내 시나리오는 수학 문제를 개발하는 것에 관한 것입니다. IProblem 인터페이스로 포함해야하는 두 가지 주요 특성은 QuestionTextResponse입니다. QuestionText는 항상 문자열 수 있지만 Response 때로는 복잡한 객체 (사용자 정의 Fraction struc) 또는 문자열, 진수, INT와 같은 다른 데이터 유형 등기본 클래스에 속성을 캡슐화하는 방법은 무엇입니까?

public interface IProblem 
    { 
     string QuestionText { get; set; } 
     object Response { get; } 

     bool IsComplete(); 
     bool IsCorrect(); 
    } 

당신이 볼 수 있듯이, Response 객체가 될 수 있습니다. 사실상 모든 문제에는 응답이 있기 때문에이 데이터 유형을 추측했습니다. 그리고 그것이 대상이기 때문에, 나는 미래의 오류 (캐스팅 문제)에 대해서만 얻을 것을 정의합니다.

나중에 캐스팅 할 필요없이이 속성 (Response)에 액세스하는 구체적인 클래스에서 아이디어가 나옵니다. 확인 해봐?

public abstract class Problem : IProblem 
    { 
     public string QuestionText { get; set;} 
     public object Response { get; protected set; } 
     public virtual bool IsComplete() 
     { 
      return true; 
     } 
     public abstract bool IsCorrect(); 
    } 

    public class BinaryProblem : Problem 
    { 
     public decimal N1 { get; set; } 
     public decimal N2 { get; set; } 
     public decimal Response 
     { 
      get { return (decimal)base.Response; } 
      set { base.Response = value; } 
     } 

     public override bool IsCorrect() 
     { 
      return N1 + N2 == Response; 
     } 
    } 

여기 값을 테스트하고 있습니다.

static void Main(string[] args) 
    { 
     BinaryProblem p = new BinaryProblem(); 
     p.N1 = 2; 
     p.N2 = 4; 

     p.Response = 6; 

     IProblem p2 = p; 
     Console.WriteLine(p2.Response); 
     Console.WriteLine(p2.IsComplete().ToString()); 
    } 

지금까지는 작동하지만, 내가하고있는 일이 올바른지 아니면 좋은 습관인지 알고 싶습니다. 나는 이것을하기 위해 다른 사람들이 new 연산자를 사용하는 것을 보았다. 다른 사람들은 base이라는 단어를 사용하지 않습니다.

좋은 방법입니까? 미래의 오류를 일으킬 수 있습니까? 제 디자인에 대한 피드백을주세요.

편집 : 비 제네릭 인터페이스에서 응답에 액세스해야합니다.

+3

개인적으로 개체에 대해 일반 또는 IResponse 인터페이스를 사용합니다. 객체를 사용하면 ResponseB는 말 그대로 StringBuilder, Int32 또는 심지어 WebRequest를 포함하는 모든 것일 수 있습니다. 인터페이스 나 Generics를 사용하면 응답을 구현하는 방법을 훨씬 더 세밀하게 제어 할 수 있습니다. – ctorx

+0

예, 및; 'Reponse'는 항상 숫자 값입니까?그런 다음 가장 적합한 수식 유형, 즉 'double'또는 'decimal'중에서 적절한 것을 사용하십시오. –

+0

@ctorx와 동의하면 Generics는 문제를 훨씬 더 명확하게 해결할 수 있습니다.이 경우 클래스 메소드/속성을 숨기고 싶지만 각 유형의 결과에 대해 diff 이름을 갖고 유형에 대해 원하는 결과 만 표시해야합니다. interface –

답변

4

어쩌면 당신은 이와 같은 것을 찾고 있습니까? 문제의 일반적인 해결책 부분 (예 : QuestionText)에 중요하지 않기 때문에 몇 가지 사항을 남겼습니다. 나는 또한 기본 클래스를 빠져 나갔다. 왜냐하면 그것은 통과 (pass-through)와 여분의 불필요한 레이어 일 것 같았 기 때문이다. 이것은 정확히 당신이 찾고있는 것이 아니지만, 나는 당신을 거기 도움이되기를 바랍니다.

우선 모든 것이 사용되는 방법입니다.
편집 : 이제는 모두 비 일반 IP 오류로 처리 될 수 있습니다.

private static void StackOverflowQuestion() 
{ 
    IProblem<int> problem1 = new IntProblem(2, 4); 
    problem1.Response = 6; 

    IProblem<decimal> problem2 = new DecimalProblem(5, 10); 
    problem2.Response = .5M; 

    Console.WriteLine("Problem 1 is correct: {0}", problem1.IsCorrect()); 
    Console.WriteLine("Problem 2 is correct: {0}", problem2.IsCorrect()); 

    List<IProblem> problems = new List<IProblem>(); 
    problems.Add(problem1); 
    problems.Add(problem2); 
    problems.ForEach(problem => Debug.WriteLine(problem.GetResponse())); 
} 

편집 : 여기

public interface IProblem 
{ 
    object GetResponse(); 
} 

인터페이스의 :
편집 : 공지 사항 여기에 많은 문제가 목록에서 사용하고 같은 방식으로 처리 할 수있는 제네릭이 아닌 인터페이스입니다 이것은 이제 비 제네릭 인터페이스를 구현합니다.
편집 :

public interface IProblem<T> : IProblem 
{ 
    T Response { get; set; } 
    bool IsCorrect(); 
} 

그리고 여기에는 클래스입니다 새로운하는 GetResponse() 메소드를 주목하라.

public class IntProblem : IProblem<int> 
{ 
    private int _number1 { get; set; } 
    private int _number2 { get; set; } 

    public int Response { get; set; } 

    public IntProblem(int number1, int number2) 
    { 
     this._number1 = number1; 
     this._number2 = number2; 
    } 

    public bool IsCorrect() 
    { 
     return this._number1 + this._number2 == Response; 
    } 

    public object GetResponse() 
    { 
     return this.Response; 
    } 
} 

public class DecimalProblem : IProblem<decimal> 
{ 
    private decimal _number1 { get; set; } 
    private decimal _number2 { get; set; } 

    public decimal Response { get; set; } 

    public DecimalProblem(decimal number1, decimal number2) 
    { 
     this._number1 = number1; 
     this._number2 = number2; 
    } 

    public bool IsCorrect() 
    { 
     return this._number1/this._number2 == Response; 
    } 

    public object GetResponse() 
    { 
     return this.Response; 
    } 
} 
+0

하나의 문제는 밥, 나는 비 제네릭 인터페이스에서 응답에 액세스하는 데 정말로 필요합니다. 당신은 그것이 큰 문제가 될 것이라고 생각합니까? –

+0

응답이 다양한 유형이 될 경우, 예제와 같이 응답을 객체로 처리해야합니다. 왜 비 제네릭 인터페이스가 필요합니까? –

+0

List 을 가지고 XMLFile에 응답을 저장할 계획이 있기 때문에 입니다. foreach를 사용하고 파일에 값을 저장하는 것과 같은 일을하고 있다고 생각했습니다. –

관련 문제