Skip to content

Instantly share code, notes, and snippets.

@kcha4github
Created August 20, 2019 01:51
Show Gist options
  • Save kcha4github/b37cdf4d6b8fc118042604d72c7449d0 to your computer and use it in GitHub Desktop.
Save kcha4github/b37cdf4d6b8fc118042604d72c7449d0 to your computer and use it in GitHub Desktop.
https://qiita.com/shoheiyokoyama/items/d752834a6a2e208b90ca よりFactory MethodをC#で写経。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FactoryMethodPatternTest
{
public abstract class Product
{
public abstract void Use();
}
public abstract class Factory
{
public Product Create(string owner)
{
Product product = createProduct(owner);
registerProduct(product);
return product;
}
protected abstract Product createProduct(string owner);
protected abstract void registerProduct(Product product);
}
public class AccountFactory : Factory
{
private List<string> owners = new List<string>();
protected override Product createProduct(string owner)
{
return new Account(owner);
}
protected override void registerProduct(Product product)
{
owners.Add(((Account)product).getOwner());
}
}
public class Account : Product
{
private string owner;
public Account(string owner)
{
Console.WriteLine("Create account: " + owner);
this.owner = owner;
}
public override void Use()
{
Console.WriteLine("Use account: " + owner);
}
public string getOwner()
{
return owner;
}
}
class Program
{
static void Main(string[] args)
{
Factory factory = new AccountFactory();
Product account1 = factory.Create("Ralph");
Product account2 = factory.Create("RIchard");
Product account3 = factory.Create("John");
Product account4 = factory.Create("Erich");
account1.Use();
account2.Use();
account3.Use();
account4.Use();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment