C#设计模式学习(类型对象模式)

实体对象类

/// <summary>
/// Monster类“ has a”Breed类,Monster类是最后实例化出来最外层的实体,即便有新的Monster,Monster也不需要做修改。
/// </summary>
public class Monster 
{
    private int health_;
    private Breed breed_;
    private string attack_;

    public Monster(Breed breed)
    {
        health_ = breed.GetHealth();
        breed_ = breed;
        attack_ = breed.GetAttack();
    }

    public string GetAttack()
    {
        return attack_;
    }
具体实现功能类
    public void ShowAttack()
    {
        Debug.Log(attack_);
    }
}

具体实现功能类

/// <summary>
/// 品种类Breed
/// </summary>
public class Breed
{
    private int health_;
    private string attack_;
    Breed parent_;
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="parent">父类</param>
    /// <param name="health">生命值,填0表示从父类继承</param>
    /// <param name="attack">攻击表现</param>
    public Breed(Breed parent, int health, string attack)
    {
        health_ = health;
        attack_ = attack;
        parent_ = null;

        //复制“代理”,在创建一个类型时将继承的特性复制到类的内部
        //注意我们不再需要parent类中的属性,一旦构造结束,就可以忘掉基类
        if (parent != null)
        {
            parent_ = parent;
        //是0,从父层拿
        if (health == 0)
        {
            health_ = parent.GetHealth();
        }
        //是null,从父层拿
        if (attack == null)
        {
            attack_ = parent.GetAttack();
        }
    }
}

public Monster NewMonster()
{
    return new Monster(this);
}

public int GetHealth()
{
    return health_;
}

public string GetAttack()
{
    return attack_;
}

}

测试主程序

using UnityEngine;
using System.Collections;

public class TypeObjectPatternExample : MonoBehaviour
{
    void Start()
    {
        //创建种类,生命值填0表示从父类继承。
        Breed troll = new Breed(null, 25, "The troll hits you!");

        Breed trollArcher = new Breed(troll, 0, "The troll archer fires an arrow!");

        Breed trollWizard = new Breed(troll, 0, "The troll wizard casts a spell on you!");

        //通过种类创建monster对象
        Monster trollMonster = troll.NewMonster();
        trollMonster.ShowAttack();

        Monster trollArcherMonster = trollArcher.NewMonster();
        trollArcherMonster.ShowAttack();

        Monster trollWizardMonster = trollWizard.NewMonster();
        trollWizardMonster.ShowAttack();

    }

}


转载自https://www.ctolib.com/Unity-Design-Pattern.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值