设计模式

父类定好模板,不同的子类只需要往里面填个性化的内容。就像一张卷子,不同的考生往里面填各自的答案。

public class TestPaper
{
    public void Question1()
    {
        Console.WriteLine("This is Question1:");
        Console.WriteLine(string.Format("Your answer is {0}", Answer1()));
    }

    public void Question2()
    {
        Console.WriteLine("This is Question2:");
        Console.WriteLine(string.Format("Your answer is {0}", Answer2()));
    }

    protected virtual string Answer1()
    {
        return string.Empty;
    }

    protected virtual string Answer2()
    {
        return string.Empty;
    }
}

public class TestPaperA : TestPaper
{
    protected override string Answer1()
    {
        return "a";
    }
    protected override string Answer2()
    {
        return "b";
    }
}

public class TestPaperB : TestPaper
{
    protected override string Answer1()
    {
        return "aa";
    }
    protected override string Answer2()
    {
        return "bb";
    }
}
public class TemplateViewModel
{
    public TemplateViewModel()
    {
        TestPaper a = new TestPaperA();
        a.Question1();
        a.Question2();
        TestPaper b = new TestPaperB();
        b.Question1();
        b.Question2();
    }
}
原文地址:https://www.cnblogs.com/MichaelLoveSna/p/14141725.html