简单工厂和抽象工厂(二次整理)
简单工厂:
上次整理过简单工厂,为了加深印象,抽时间又再次整理了一下.
简单工厂的创建一般为以下几个步骤:
1).创建父类(虚方法或抽象方法)
Abstract/virture
2).创建子类(继承父类,一般都重写父类方法以达到所需效果)
override
2.1).添加一个枚举类型(可以不需要,便于传入参数,在工厂中被判断)
3).创建工厂(传入一个所需物体的参数(可以为枚举),传出一个物体对象,就像一个工厂一样)
4).实现
废话不多说,代码走起!
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MySimpleFactory : MonoBehaviour { void Start () { FatherMobliePhone APhone = MobliePhoneFactory01.CreatMiblePhone(PhoneType01.iphone); APhone.ToDo(); } void Update () { } } //创建父类 public abstract class FatherMobliePhone { public abstract void ToDo(); } //子类继承父类 public class Iphone : FatherMobliePhone { public override void ToDo() { Debug.Log("My Name Is Iphone ."); } } public class HuaWei : FatherMobliePhone { public override void ToDo() { Debug.Log("My Name Is HuaWei ."); } } public class ViVo : FatherMobliePhone { public override void ToDo() { Debug.Log("My Name Is ViVo ."); } } //创建枚举类型 public enum PhoneType01 { iphone, ViVo, HuaWei } //创建工厂 public class MobliePhoneFactory01 { //传入一个手机类型,在此返回的是一个手机对象!!!! public static FatherMobliePhone CreatMiblePhone(PhoneType01 MyType) { FatherMobliePhone mMobliePhone =null; switch (MyType) { case PhoneType01.iphone: mMobliePhone=new Iphone(); break; case PhoneType01.ViVo: mMobliePhone = new ViVo(); break; case PhoneType01.HuaWei: mMobliePhone = new HuaWei(); break; default: break; } return mMobliePhone; } }
抽象工厂:
看过了简单工厂就来感受一下抽象工厂.抽象工厂也就是工厂方法(特点:一个物体对应一个工厂,工厂具体化,企业化!)
先来看一下大体思路:
代码展示:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AbstractFactoryTest : MonoBehaviour//实现 { void Start () { AbstractFactory xiaomiFactory= new XiaomiFactory(); MotherBoard motherBoard = xiaomiFactory.CreateMotherBoard(); motherBoard.Print(); Screen screen = xiaomiFactory.CreateScreen(); screen.Print(); } void Update () { } } public abstract class AbstractFactory// 抽象工厂父类 { public abstract Screen CreateScreen(); public abstract MotherBoard CreateMotherBoard(); } public abstract class Screen// 抽象屏幕父类 { public abstract void Print(); } public abstract class MotherBoard// 抽象主板父类 { public abstract void Print(); } //继承屏幕的子类 public class AppleScreen : Screen { public override void Print() { Debug.Log("苹果手机屏幕"); } } public class XiaoMiScreen : Screen { public override void Print() { Debug.Log("小米屏幕"); } } //继承主板的子类 public class AppleMotherBoard : MotherBoard { public override void Print() { Debug.Log("苹果主板"); } } public class XiaoMiMotherBoard : MotherBoard { public override void Print() { Debug.Log("小米主板"); } } public class AppleFactory : AbstractFactory//继承主工厂的子类---->苹果专用 { public override MotherBoard CreateMotherBoard() { return new AppleMotherBoard(); } public override Screen CreateScreen() { return new AppleScreen(); } } public class XiaomiFactory : AbstractFactory//继承主工厂的子类---->小米专用 { public override MotherBoard CreateMotherBoard() { return new XiaoMiMotherBoard(); } public override Screen CreateScreen() { return new XiaoMiScreen(); } }