网站应包括的基本功能和高级功能,通化网站建设,抖音小程序源码,有哪个网站做正品港货简单工厂模式又称为静态工厂模式#xff0c;其实就是根据传入参数创建对应具体类的实例并返回实例对象#xff0c;这些类通常继承至同一个父类#xff0c;该模式专门定义了一个类来负责创建其他类的实例。
using System.Collections;
using System.Collections.Generic;
us…
简单工厂模式又称为静态工厂模式其实就是根据传入参数创建对应具体类的实例并返回实例对象这些类通常继承至同一个父类该模式专门定义了一个类来负责创建其他类的实例。
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;}
}
优点将对象的创建于使用分离创建完全交给工厂类来实现。
缺点违反了开闭原则即对修改关闭对拓展开放当有新的具体类需要创建时都需要修改工厂类中的创建方法多增加判断。