Home  /  Questions  /  Question



0   0
Jun 19, 2016


How to Implement Two Way Observer on same Class

Hello
I am trying to use the observer pattern to move the cloned Object (Prototype) when the Original is moved.But i am not doing anything. Bellow is the code that i am trying to use.When i try to subscribe a new object and moving the original doesn't affect the subscriber
What am i doing wrong.
public abstract class AbstractShape :ISubject ,IObserver
    {
        //  private List<IShapeClone> clones = new List<IShapeClone>();
        public Dimensions _Dimension;
        public Positions _Position ;
        public virtual ColorEnum Color { get; set; }
        public abstract void Show();
        public Move m;
        internal List<AbstractShape> observers = new List<AbstractShape>();
        protected int _id;
        public int Id
        {
            get
            {
                return _id;
            }
        }
        public abstract void Subscribe(AbstractShape observer);
        public abstract void Unsubscribe(AbstractShape observer);
        public abstract void Notify();
        public abstract List<AbstractShape> Update();
   
    }

public class Circle : AbstractShape
    {
        public Circle(Dimensions _CircleDimension, Positions _CirclePosition, ColorEnum Color)
        {
            _id = SequenceNumberGenerator.GetInstance().SequenceNumber;
            _Dimension = _CircleDimension;
            _Position = _CirclePosition;
            this.Color = Color;
        }

         public override void Show()
        {
            Console.WriteLine("This is a circle with radius of {0},and position of ({1},{2}) and color of {3} ,has the id of {4}", _Dimension.R, _Position.x, _Position.y,Color ,_id);
        }
      
        public Circle DeepClone(int x,int y)
        {
            Circle deepCopyCircle = new Circle(_Dimension,new Positions (_Position.X+x,_Position.Y+y), Color);
            return deepCopyCircle;
        }

        public override List<AbstractShape> Update()
        {
            List<AbstractShape> circleUpdate = new List<AbstractShape>();
            for (int i = 0; i < observers.Count; i++)
            {
                Circle c = (Circle)observers[i];
                c.Color = Color;
                c._Dimension= _Dimension;
                c._Position.X = _Position.X+10;
                c._Position.Y = _Position.Y + 10;
                circleUpdate.Add(c);
            }
            return circleUpdate;
            
        }

        public override void Notify()
        {
            observers.ForEach(x => x.Update());
        }

        public override void Unsubscribe(AbstractShape observer)
        {
            observers.Remove(observer);
        }

        public override void Subscribe(AbstractShape observer)
        {
            observers.Add(observer);
        }

    }