设计模式模板
1.工厂模式
1.1new同类型东西比较多的时候用到
1.2几点功能
1.2.1加载资源
1.2.2初始化
1.2.3放到合适的位置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 工厂
/// </summary>
public class Factory {
Sprite[] allSprit;
Transform parent;
public Factory()
{
Initial();
}
public void Initial()
{
allSprit = Resources.LoadAll<Sprite>("1534238263(1)");
parent = GameObject.FindWithTag("MainCanvas").transform;
}
public GameObject CreatrImage(int index,Vector3 pos)
{
GameObject tmpObj = new GameObject();
//判断是否超过数组长度
index = index % allSprit.Length;
tmpObj.AddComponent<Image>().sprite=allSprit[index];
tmpObj.transform.SetParent(parent,false);
tmpObj.transform.localPosition = pos;
return tmpObj;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 使用工厂
/// </summary>
public class UseFactory : MonoBehaviour {
Factory useFactory;
void Start () {
useFactory = new Factory();
}
int index = 0;
void Update () {
if (Input.GetKeyDown(KeyCode.A))
{
index++;
Vector3 v = Vector3.one * index*100;
useFactory.CreatrImage(index, v);
}
}
}
2.观察者模式
模拟播放动画
2.1当动画播放完毕时,播放一个粒子特效。由于我们不知道什么时候播放完成,所以需要一直询问(下图示例)。
image.png
3.代理模式
image.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class AnimalPlayer:MonoBehaviour
{
UnityAction AnimalDelegate;
//public delegate void AnimalDelegate();
public Animation animal;
public AnimalPlayer(Animation ani,UnityAction action)
{
animal = ani;
AnimalDelegate = action;
}
public void Play(string name)
{
animal.Play(name);
}
public bool isTrigger=false;
private void Update()
{
//如果动画播放完毕,调用callback
if (!animal.IsPlaying("")&&isTrigger)
{
AnimalDelegate();
isTrigger = true;
}
}
}
public class DelegateModle : MonoBehaviour {
public AnimalPlayer animalPlayer;
public Animation ani;
public void CallBack()
{
Debug.Log("进入回调");
}
void Start () {
animalPlayer = new AnimalPlayer(ani, CallBack);
}
}
单例模式:
整个软件生命周期有且只有一个
拖拽到物体身上相当于new的操作,拖拽两次就是new两次
只能挂载到一个物体身上
非继承Mono的单例
image.png
策略模式
image.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 策略模式
/// 通过多态实现,父类的指针指向子类的方法
/// </summary>
public class StrategyBase : MonoBehaviour {
public float playerTax;
public virtual void CaculaeTax()
{
}
}
public class PersonStrage : StrategyBase
{
public override void CaculaeTax()
{
//base.CaculaeTax();
playerTax *= 0.08f;
}
}
public class CompaneyStrage : StrategyBase
{
public override void CaculaeTax()
{
playerTax *= 0.12f;
//base.CaculaeTax();
}
}
public class Strage : MonoBehaviour
{
public void CaculaeTax(StrategyBase tmpBase)
{
tmpBase.CaculaeTax();
}
private void Start()
{
PersonStrage personStrage = new PersonStrage();
CaculaeTax(personStrage);
CompaneyStrage companeyStrage = new CompaneyStrage();
CaculaeTax(companeyStrage);
}
}