命立模式:将方法独立出来,进行是实例化,方便指针回调
例子:
输入A 输出A
输入B 输出B
class Program {
static void Main(string[] args) {
Player player = new Player();
string inputValue = null;
Console.WriteLine("请输入按键");
inputValue = Console.ReadLine();
Console.WriteLine($"输入的按键为{inputValue}");
Console.WriteLine("输出的事件为");
if (inputValue == "A"||inputValue=="a")
{
player.OutputA();
}
else if (inputValue=="B"||inputValue=="b")
{
player.OutputB();
}
else
{
Console.WriteLine("输入无效操作");
}
}
}
class Player {
public void OutputA() {
Console.WriteLine("A");
}
public void OutputB() {
Console.WriteLine("B");
}
}
现在要更改为
输入A 输出B
输入B 输出A
现情况,除了打开原编码,并没有好的办法
解决的答案就是,调用的时候,使用方法指针进行调用,即在每次程序运行之前,先让指针与方法进行配队,随后输入A,即调用A指针,输入B,即调用B指针。为了使编码更清晰,可以把被指向的方法单独进行实例化
class Program {
static void Main(string[] args) {
int settingValue = 0;
Player player = new Player();
Console.WriteLine("输入设定情况");
settingValue = int.Parse(Console.ReadLine());
Console.WriteLine(settingValue);
if (settingValue == 1)
{
Console.WriteLine($"A输出A,B输出B");
player.button_a = new OutputA();
player.button_b = new OutputB();
Console.WriteLine();
}
else if (settingValue == 2)
{
Console.WriteLine($"A输出B,B输出A");
player.button_a = new OutputB();
player.button_b = new OutputA();
Console.WriteLine();
}
else
{
Console.WriteLine("无效输入");
}
string inputValue = null;
Console.WriteLine("请输入按键");
inputValue = Console.ReadLine();
Console.WriteLine($"输入的按键为{inputValue}");
Console.WriteLine();
Console.WriteLine("输出的事件为");
if (inputValue == "A" || inputValue == "a")
{
player.button_a.doSomething();
}
else if (inputValue == "B" || inputValue == "b")
{
player.button_b.doSomething();
}
else
{
Console.WriteLine("输入无效操作");
}
}
}
interface ICommand {
void doSomething();
}
class OutputA : ICommand {
public void doSomething() {
Console.WriteLine("A");
}
}
class OutputB : ICommand {
public void doSomething() {
Console.WriteLine("B");
}
}
class Player {
public ICommand button_a;
public ICommand button_b;
}
因为C#中基本不会使用方法指针,所以使用接口来引用。
另外在游戏设定中,会有更好的方法来进行这种按键与输出之间的映射
这里只是单独的理解命立模式
通过上述例子,可以基本得出的结论就是:
1.使用命立模式的本质就是方法的回调,所以通过接口也可以实现方法的回调
2.使用命立模式的方法,是性质相近的,或者说是处理同一系列事情的方法
3.使用命立模式的时候,先声明一个接口,当然也可以是一个基类,不过为了代码的清晰,统一使用接口会好点。然后实现接口。创建接口变量,根据映射来进行变量的实例化,方法的调用是使用接口变量进行的方法调用
4.总的来说命立就是实例化的方法调用