program.cs

来自「GOF23种设计模式详细例子!附有详细的代码噢!」· CS 代码 · 共 106 行

CS
106
字号
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace MementoExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Enemy enemy = new Enemy(1, 2, new Location(10, 20));
            BackupCenter bc = new BackupCenter();
            Guid bak1 = bc.Save(enemy);
            enemy.Location = new Location(20, 30);
            enemy.Power = 3;
            Guid bak2 = bc.Save(enemy);
            enemy.Speed = 4;
            enemy.ShowInfo();
            bc.Load(bak1).ShowInfo();
            bc.Load(bak2).ShowInfo();
        }
    }

    class BackupCenter
    {
        private Dictionary<Guid, Enemy> backupData = new Dictionary<Guid, Enemy>();

        public Guid Save(Enemy enemy)
        {
            Guid guid = Guid.NewGuid();
            backupData.Add(guid, enemy.Clone());
            return guid;
        }

        public Enemy Load(Guid guid)
        {
            Console.WriteLine("Load " + guid.ToString());
            return backupData[guid];
        }
    }

    [Serializable]
    class Location
    {
        public int x;
        public int y;

        public Location(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    [Serializable]
    class Enemy
    {
        protected Location location;

        public Location Location
        {
            get { return location; }
            set { location = value; }
        }

        protected int power;

        public int Power
        {
            get { return power; }
            set { power = value; }
        }

        protected int speed;

        public int Speed
        {
            get { return speed; }
            set { speed = value; }
        }

        public Enemy(int power, int speed, Location location)
        {
            this.power = power;
            this.speed = speed;
            this.location = location;
        }

        public Enemy Clone()
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, this);
            memoryStream.Position = 0;
            return (Enemy)formatter.Deserialize(memoryStream);
        }

        public void ShowInfo()
        {
            Console.WriteLine("power:{0} speed:{1} location:({2},{3})", power, speed, location.x, location.y);
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?