Design patterns – Strategy

Strategy pattern is a behavioral pattern. It defines group of algorithms which do the same thing, but different way. It keeps the algorithm independent from it’s caller.
Imagine you want to serialize data in different ways: to XML and to binary data.

Our strategies with interface.

    interface ISerializationStrategy
    {
        string Serialize(object x);
    }
	
    /// <summary>
    /// Serialization strategy to serialize object to xml
    /// </summary>
    class XmlSerializationStrategy : ISerializationStrategy
    {
        public string Serialize(object x)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(object));
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, x);
                return writer.ToString();
            }
        }
    }
	
    /// <summary>
    /// Serialization strategy to serialize object to binary
    /// </summary>
    class BinarySerializationStrategy : ISerializationStrategy
    {
        public string Serialize(object x)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            using (var stream = new MemoryStream())
            using (var reader = new StreamReader(stream))
            {
                formatter.Serialize(stream, x);
                stream.Position = 0;
                return reader.ReadToEnd();
            }
        }
    }

Our strategy context which uses strategies.

    /// <summary>
    /// Context which uses one of serialization strategy.
    /// </summary>
    class SerializationContext
    {
        private ISerializationStrategy _strategy;

        public SerializationContext(ISerializationStrategy strategy)
        {
            _strategy = strategy;
        }

        public void PerformSerialization(object x)
        {
            Console.WriteLine(_strategy.Serialize(x));
        }
    }

Usage example:

        public static void StrategyUsage()
        {
            var strategyXml = new XmlSerializationStrategy();
            var strategyBinary = new BinarySerializationStrategy();

            var contextA = new SerializationContext(strategyXml);
            var contextB = new SerializationContext(strategyBinary);

            contextA.PerformSerialization("Test");
            contextB.PerformSerialization("Test");
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s