简单工厂模式又称为静态工厂模式,其实就是根据传入参数创建对应具体类的实例并返回实例对象,这些类通常继承至同一个父类,该模式专门定义了一个类来负责创建其他类的实例。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//父类接口
public interface Animal
{
void Eat();
}
//猫子类
public class Cat : Animal
{
public void Eat()
{
Debug.Log("猫");
}
}
//狗子类
public class Dog : Animal
{
public void Eat()
{
Debug.Log("狗");
}
}
这就是工厂类,提供一个方法创建具体类的实例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Factory
{
public static Animal CreatAnimal(string animal)
{
Animal animalObj = null;
switch (animal)
{
case "cat":
animalObj = new Cat();
break;
case "dog":
animalObj = new Dog();
break;
}
return animalObj;
}
}
优点:将对象的创建于使用分离,创建完全交给工厂类来实现。文章来源:https://www.toymoban.com/news/detail-652058.html
缺点:违反了开闭原则(即对修改关闭,对拓展开放),当有新的具体类需要创建时都需要修改工厂类中的创建方法,多增加判断。 文章来源地址https://www.toymoban.com/news/detail-652058.html
到了这里,关于设计模式-简单工厂模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!