はじめに
以下の記事にてDIシステムへの型登録を動的に行う方法について解説しましたが、今回の記事ではGoFのデザインパターンの1つであるFactoryパターンを用いて同様の処理を書いていこうと思います。
(Factoryパターンについても以前記事を作成したので載せておきます)
サンプルコード
まずはFactoryを作っていきます。
上記に添付したFactoryパターンの記事内で解説している構成要素は以下のような感じになります。
Product: IAnimalインターフェース
ConcreteProduct: Dogクラス, Catクラス
Creator: IFactoryインターフェース
ConcreteCreator: AnimalFactoryクラス
AnimalFactory.cs
// Product
public interface IAnimal
{
void Nakigoe();
}
// ConcreteProduct
public class Dog : IAnimal
{
public void Nakigoe() => Console.WriteLine("ワンワン!");
}
// ConcreteProduct
public class Cat : IAnimal
{
public void Nakigoe() => Console.WriteLine("にゃー!");
}
// Creator
public interface IFactory
{
public IAnimal Create();
}
// ConcreteCreator
public class AnimalFactory : IFactory
{
public string Animal { get; }
public AnimalFactory(string animal) => Animal = animal;
public IAnimal Create()
{
switch (Animal)
{
case "Dog":
return new Dog();
default:
return new Cat();
}
}
}
Startup.csも以前に比べてスッキリしました。
前回はこちらのほうで条件分岐後にnew Dog()やらnew Cat()などしていましたが、今回はそれらは全てAnimalFactoryクラスへ任せています。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// appsettings.jsonから動物を選択
var animal = Configuration.GetSection(NakigoeConfig.SectionName).Get<NakigoeConfig>().Animal;
services.AddSingleton(provider =>
{
return new AnimalFactory(animal).Create();
});
}
おわりに
「なるべく各メソッドには本来やるべき処理のみを記載する」ということを徹底してより良いコードが書けるよう精進していきたいと思います!
↧