Tôi là người mới và cố gắng hiểu khái niệm về mẫu kế thừa và thiết kế.Truyền lớp bắt nguồn làm tham số cho một phương thức khi kiểu tham số là lớp cơ sở
Tôi đã xem mẫu này http://en.wikipedia.org/wiki/Strategy_pattern khi tôi xem qua một số blog.
Tôi thấy nó thú vị và muốn tìm hiểu thêm. Vì vậy, tôi đã phát triển chương trình sau.
static void Main(string[] args)
{
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3, 4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3, 4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3, 4);
Console.Read();
}
abstract class Strategy
{
public abstract int execute(int a, int b);
public void Test()
{
Console.Write("tttt");
}
}
class ConcreteStrategyAdd : Strategy
{
public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategyAdd's execute()");
return a + b; // Do an addition with a and b
}
}
class ConcreteStrategySubtract : Strategy
{
public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategySubtract's execute()");
return a - b; // Do a subtraction with a and b
}
}
class ConcreteStrategyMultiply : Strategy
{
public override int execute(int a, int b)
{
Console.WriteLine("Called ConcreteStrategyMultiply's execute()");
return a * b; // Do a multiplication with a and b
}
}
class Context
{
private Strategy strategy;
// Constructor
public Context(Strategy strategy)
{
this.strategy = strategy;
}
public int executeStrategy(int a, int b)
{
return strategy.execute(a, b);
}
}
Chương trình biên dịch tốt và đang hoạt động. Nhưng câu hỏi của tôi là làm thế nào là nó có thể vượt qua lớp dẫn xuất như một tham số khi các nhà xây dựng Context
là mong đợi lớp cơ sở như một tham số? Việc đúc diễn ra có ngầm không? Tại sao trình biên dịch không lỗi?
context = new Context(new ConcreteStrategyAdd());
public Context(Strategy strategy)
{
this.strategy = strategy;
}
+1 cho một câu hỏi mới bắt đầu tốt! –
Đối với một newbie, bạn đang hỏi tất cả các câu hỏi đúng :) +1 – MattDavey