sabato 4 maggio 2019

My cyberdeck

This is my version of Cyberdeck from the dystropian future of William Gibson.
It is raspberry pi2 + arduino micro + 50W audio amply and double LCD display.
Portable.


Design Pattern : Flyweight Pattern

Flyweight Pattern is user to reduce the amount or memory when you have many objects with a common part. So you separate the common part from the specialized part of the object and you reuse the common parte for all object.
For example you can create a cache class that stores a list of objects, these objects are common and you don't need to instantiate a new object if it is already instantiated previously. The Classic example is a Word processore that uses characters. The characters have a common part: font,size,color, and a specificare part, the characters itself : 'a', 'b', etc and when you use the characters 'a' you don't have to recreate the object again when you use it a second time.

class Character
{
    int size;
    string font;
    Color color;

    public void Character()
    {
         size = 8;
         font = "Verdana";
         color = Color.Red;
    }
}

public class CharacterA : Character
{
    char character;
   
    public void CharacterA()
    {
         character = 'A';
    }
}

public class CharacterB : Character
{
    char character;
   
    public void CharacterB()
    {
         character = 'B';
    }
}

...

public class CharacterFactory
{
    private Dictionary<char,Character> characterMap;
    ...
    public Character GetCharacter(char character)
   {
        Character characterToReturn;
        if (characterMap.ContainsKey(character))
        {
             characterToReturn = characterMap[character];
        }
        else
       {
             switch(character)
             {
                   case 'A':
                       characterToReturn = new CharacterA();
                   case 'B':
                        characterToReturn = new CharacterB();
                   ...
             }
             characterMap[character] = characterToReturn;
       }

       return characterToReturn;
   }
}

domenica 28 aprile 2019

Design Patterns : State Pattern

State pattern defines a way to manage a state machine, if you don't use design patterns, in traditional programming, you will use a switch statement to move throw the states.
You have to create an interface with a method for the action to do in a specific state, then you have to create concreate classes for each state and implement the method to implement the state, then you need a context to switch the states. The client will use the context to change the states.

public interface IStatus
{
     void ApplyStatus();
}

public class StateInit : Status
{
     void ApplyStatus()
     {
           InitializeMachine();
     }
}

public class StateRunning : Status
{
     public void ApplyStatus()
     {
           RunMachine();
     }
}

public class StateStop : Status
{
     public void ApplyStatus()
     {
           StopMachine();
     }
}

public class Context
{
      private Status state,

      public void SetStatus(Status status)
      {
            state = status;
      }

      public ChangeStatus()
     {
           state.ApplyStatus();
     }
}

Usage:
Contex contex;
context.SetStatus(new StateInit());
context.ChangeStatus();
context.SetStatus(new StateRunning());
context.ChangeStatus();
context.SetStatus(new StateStop());
context.ChangeStatus();

sabato 27 aprile 2019

Design Patterns : Factory Pattern


Factory pattern is a pattern to create objects from a factory, when 2 objects are similar, to avoid casting.
You have to create an abstract base class with some methods and one or more concrete classes that inherit the base class, then you have to create a factory class that has a method that return a base class, the class returned is based on the parameters of the method.

abstract class Vehicle
{
       public abstract Run();
}

class Car : Vehichle
{
      public override Run()
      {
          // implement run for a car
      }
}

class Motorcycle : Vehichle
{
      public override Run()
      {
          // implement run for a motorcycle
      }
}

class NullMobile : Vehichle
{
      public override Run()
      {
          // do nothing
      }
}


public static class Factory
{
       public Vehicle GetVehicle(string type)
      {
            if (type.Equals("car"))
                   return new Car();
            else if (type.Equals("motorcycle"))
                   return new Motorcycle();
            else
                   return new NullMobile();
      }
}

Usage:
var newCar = Factory.GetVehicle("car);
 newCar.Run();

Design Patterns : Singleton

Singleton is very easy design pattern, it is used to instantiate an object only 1 time in the application.
It's like a static member.
You have to create a class and add a private member of the same class (the instance of the class), then you have to set private the constructor and add a method to get the instance that creates a new instance if not already created, otherwise it returns the private member.

static class Singleton
{
       private static Singleton instance;
   
       pubic static GetInstance()
       {
              if (instance == null)
                    instance = new Singleton();
              return instance;
       }
}

Usage:

var mySingleton1 = Singleton.GetInstance();
var mySingleton2 = Singleton.GetInstance(); // in another module
and the result is mySingleton1 = mySingleton2

Design Patterns: Composite Patter

Composite patter essentially implements a tree of objects and you can use it everytime you need a tree data structure.
At first you define a class for a node with private information for the node and the list of child node. In the constructor you pass the information to create the node, also you need a method to add a child node that add the child node in the private list of child nodes and also a method to get all the child nodes. You also need an class for the root node to create the tree. the root node class has a private node that is the root node. you need a method to get this root node, then you call rootnode.add to add child nodes to root node and build the tree. A classic use of composite pattern is associated to the filesystem that is a tree data structure.

public class Node
{
      private NodeInfo nodeInfo;
      private List<Node> childNodes;
      public void Node(NodeInfo info)
     {
           nodeInfo = info;
           childNodes = new List<Node>();
     }

     public NodeInfo GetInfo()
    {
           return nodeInfo;
    }

     public void Add(Node node)
     {
            childNodes.Add(node);
     }

     public IEnumerable<Node> GetChildNodes()
    {
            foreach(var node in childNodes)
                   yield return node;
    }

}

pubic class Root
{
      private Node root;

      public Root(Node node)
      {
             root = node;
      }

      public Node getRoot()
      {
             return root;
      }
}

Usage:
var rootNode = new Node(nodeInfo);
var firstChild = new Node(nodeInfo1);
var secondChild = new Node(nodeInfo2);
var tree = new Root(rootNode);
var node = tree.getRoot(),
node.Add(firstChild);
node.Add(secondChild);
foreach(n in node.GetChildNodes())
     Console.WriteNode(n);

Design Patterns: Strategy Pattern

In the latest years design pattern programming seems a must if you want to work in a development team, especially java and C#. What I think is that a good programmer only need common sense.

This is very simplified explanation of strategy pattern:
Strategy pattern is when you want use different strategy or algorithms to process data. For example you want to use different types of sort: quick sort, bubble sort,etc, in this case the strategy is the sort algorithm. You have to create an abstract class Strategy with a method to apply the strategy, then you have to implement the strategies classes inherit from Strategy class that overload the same method with their strategy.
At the end you have to create a context class that has a private Strategy member, in the constructor you pass the strategy class (Ex: quick sort) and a method to implement the strategy that will call the strategy.strategy method.

public abstract class Strategy
{
public abstract double applyAlgorithm(int a,int b),
}

public class FirstAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class SecondAlghorithm extends Strategy
{
@Override
         public double ApplyAlgorithm(int a,int b)
         {
// do calculation
}
}

public class Context
{
         private Strategy strategy,
   
         public Context(Strategy strategy)
         {
                this.strategy = strategy;
         } 

         public double applyAlgorithm(int a,int b)
         {
return strategy.ApplyAlgorithm(a,b);
}
}

Usage:

Context ctx = new Context( new FirstStrategy());

double result = ctx.ApplyAlgorithm( 4, 2);


In case of sorting strategies the previous example  become:

public abstract class StrategySort
{
public abstract void Sort(int[] array),
}

public class MergeSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do merge sort in array
}
}

public class QuickSort extends StrategySort
{
@Override
        public void Sort(int[] array)         
        {
// do quicksort in array
}
}

public class Context
{
         private StrategySort strategy,
   
         public Context(StrategySort strategy)
         {
                this.strategy = strategy;
         } 

        public void Sort(int[] array)         
        {
strategy.Sort(array);
}
}

Usage:

Context ctx = new Context( new QuickSort());

double result = ctx.Sort(array);