참고자료 : 챌린지반 디자인패턴 강의노트
public interface ICommand
{
void Execute();
void Undo();
}
public class MoveCommand : ICommand
{
private Transform _player;
private Vector3 _direction;
private Vector3 _previousPosition;
public MoveCommand(Transform player, Vector3 direction)
{
_player = player;
_direction = direction;
}
public void Execute()
{
_previousPosition = _player.position;
_player.position += _direction;
}
public void Undo()
{
_player.position = _previousPosition;
}
}
public class CommandInvoker
{
private Stack<ICommand> _commandHistory = new Stack<ICommand>();
public void ExecuteCommand(ICommand command)
{
command.Execute();
_commandHistory.Push(command);
}
public void UndoCommand()
{
if (_commandHistory.Count > 0)
{
ICommand command = _commandHistory.Pop();
command.Undo();
}
}
}
public class PlayerController : MonoBehaviour
{
private CommandInvoker _invoker;
private Transform _playerTransform;
void Start()
{
_invoker = new CommandInvoker();
_playerTransform = this.transform;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
ICommand moveUp = new MoveCommand(_playerTransform, Vector3.up);
_invoker.ExecuteCommand(moveUp);
}
if (Input.GetKeyDown(KeyCode.S))
{
ICommand moveDown = new MoveCommand(_playerTransform, Vector3.down);
_invoker.ExecuteCommand(moveDown);
}
if (Input.GetKeyDown(KeyCode.Z))
{
_invoker.UndoCommand();
}
}
}
public class OriginalObject
{
public string String1 { get; set; }
public string String2 { get; set; }
public OriginalObject(string str1, string str2)
{
this.String1 = str1;
this.String2 = str2;
}
public void SetMemento(Memento memento)
{
this.String1 = memento.string1;
this.String2 = memento.string2;
}
public Memento CreateMemento()
{
return new Memento(this.String1, this.String2);
}
}
//Memento object
public class Memento
{
public readonly string string1;
public readonly string string2;
public Memento(string str1, string str2)
{
this.string1 = str1;
this.string2 = str2;
}
}
//CareTaker Object
public class CareTaker
{
public Memento Memento { get; set; }
}
//Client
class Program
{
static void Main(string[] args)
{
// Create Originator object which container first state of "First" and "One".
// The Memento will remember these value.
OriginalObject original = new OriginalObject("First", "One");
// Create first State and store to caretaker
Memento firstMemento = original.CreateMemento();
CareTaker caretaker = new CareTaker();
caretaker.Memento = firstMemento;
// Change into second state; "Second" and "Two".
original.String1 = "Second";
original.String2 = "Two";
// Retrieve back first State
original.SetMemento(caretaker.Memento);
}
}