LoginSignup
3
0

More than 3 years have passed since last update.

デザインパターン入門_Template Method

Last updated at Posted at 2019-07-12

Javaで学ぶデザインパターン入門

結城浩「Javaで学ぶデザインパターン入門」をC#で勉強

Template Methodパターン

スーパークラスで処理の枠組みを定め、サブクラスでその具体的内容を定めるパターン

実装

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPatternLearn.TemplateLearn
{
    public class TemplateLearn
    {
        public static void Main(string[] args)
        {
            AbstractDisplay d1 = new CharDisplay('A');
            AbstractDisplay d2 = new StringDisplay("Hello, World!");
            d1.Display();
            d2.Display();
            Console.Read();
        }
    }

    public abstract class AbstractDisplay
    {
        public abstract void Open();
        public abstract void Print();
        public abstract void Close();
        public void Display()
        {
            Open();
            for (int i = 0; i <= 5; i++)
            {
                Print();
            }
            Close();
        }
    }

    public class CharDisplay : AbstractDisplay
    {
        private char Ch { get; set; }

        public CharDisplay(char ch)
        {
            this.Ch = ch;
        }

        public override void Open()
        {
            Console.Write("<<");
        }

        public override void Print()
        {
            Console.Write(this.Ch);
        }
        public override void Close()
        {
            Console.WriteLine(">>");
        }
    }

    public class StringDisplay : AbstractDisplay
    {
        private string Str { get; set; }
        private int Width { get; set; }

        public StringDisplay (string str)
        {
            this.Str = str;
            this.Width = this.Str.Length;
        }

        public override void Open()
        {
            PrintLine();
        }

        public override void Print()
        {
            Console.WriteLine("|" + Str + "|");
        }

        public override void Close()
        {
            PrintLine();
        }

        private void PrintLine()
        {
            Console.Write("+");
            for (int i = 0; i < Width; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("+");
        }
    }
}

重要な点

抽象クラス(AbstractDisplay)でテンプレートメソッド(共通した処理の流れ)を実装し、テンプレート メソッドで使用するメソッドは具象クラス(CharDisplay, StringDisplay)で実装する。これにより、テンプレートメソッド(共通した処理の流れ)に問題が見つかっても、修正が少なくて済む。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0