0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でかみ砕いたデザインパターン:TemplateMethod

Last updated at Posted at 2019-10-02

過去に教えて頂いたデザインパターンの一つ
テンプレートメソッドパターンをアウトプット
(間違ってるかも)

[デザインパターン:TemplateMethod]
(https://qiita.com/shoheiyokoyama/items/c2ce16b4f492cd014d50#abstract)
を参考にJAVAをC#に変えて記述にしております。

Class1.cs

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

namespace Class1
{
    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 < 3; i++)
            {
                Print();
            }
            Close();
        }
    }
    public class CharDisplay : AbstractDisplay
    {
        char ch;
        public CharDisplay(char ch)
        {
            this.ch = ch;
        }

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

        public override void Print()
        {
            Console.Write(ch);
        }

        public override void Close()
        {
            Console.WriteLine("***");
        }
    }
    public class StringDisplay : AbstractDisplay
    {
        private string str;
        private int width;
        public StringDisplay(string str)
        {
            this.str = str;
            this.width = str.Length;
        }
        void PrintLine()
        {
            Console.Write("+");
            for (int i = 0; i < width; i++)
            {
                Console.Write("-");
            }
            Console.WriteLine("+");
        }

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

        public override void Print()
        {
            Console.WriteLine("|" + str + "|");
        }
        public override void Close()
        {
            PrintLine();
        }
    }
}

Program.cs

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            AbstractDisplay cd = new CharDisplay('T');
            cd.Display();
            AbstractDisplay sd = new StringDisplay("Design Pattern");
            sd.Display();

        }
    }
}

23/1個目

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?