onsdag 11 december 2013

Design Patterns: Singleton

The most basic of all design patterns is the singleton,

From Wikipedia, "In software engineering, the singleton pattern is a design pattern that restricts the Instantiation of a class to one object."

This means that we can only create ONE instance of a class and that instance should be reused.


public class MySingleton {
   private static MySingleton instance = null;
   protected MySingleton() {
      // Exists only to defeat instantiation.
   }
   public static MySingleton getInstance() {
      if(instance == null) {
         instance = new MySingleton();
      }
      return instance;
   }
}
As can be seen in the example code, this class is a static class containing static methods. When you want to create an instance of the singleton class you call MySingleton.getInstance().
This method check if the static field instance is null, and if it is null then it creates a new instance using the keyword new and return the new instance. In case there already is an instance, we return it directly.

We can't create an instance of MySingleton by using MySingleton myInstance = new MySingleton() since the constructor is defined as protected (only reachable from the class it self, and not by any other class)

Known uses:
- Logging class
- Utility classes


Singleton is considered bad in many cases but it is a fundamental design pattern that everybody should know about.

söndag 8 december 2013

Checkio: House Password

My solution for Checkio assignment House Password:
def checkio(data):
        returnValue = True
        if (len(data) < 10) or (re.search("[A-Z]", data) == None) or (re.search("[a-z]", data) == None) or (re.search("[0-9]", data)) == None:
            returnValue = False
        return returnValue; 

lördag 7 december 2013

Checkio: Non-unique elements

My solution for the second problem (called Non-unique elements) in checkio:
def checkio(data):
    return [x for x in data if data.count(x) >= 2]

Checkio: Extra dashes

My solution for the first problem in Checkio (http://www.checkio.com)
def checkio(line):
    return "-".join([x for x in line.split("-") if x != ""])

difference between weeks

Example, if you have a course that start one week and ends after 10 weeks, and you want to calculate which week you current are in your course.
$currentWeek = strtotime("2013W51");
$startWeek = strtotime("2013W54");
$difference = $currentWeek - $startWeek;

$currentWeek =  date('W', $c);

fredag 6 december 2013

Design Pattern: Builder

This builder design pattern is not the one described by Gang of Four, but a common way to build things in Java.

As you create a java class, you also define a static builder class, which holds the exact same fields as your original Java class.

For each field in the builder class, define a setter-method that sets the value specified on correct field, and return the it self (the builder object).
At the end you define a build-method that returns a new instance of the original class.

class Fudge {

 private final int condensedMilk;
 private final String chocolateType;

    public static class Builder {

  //exact same fields as in the original class
  private int condensedMilk;
  private String chocolateType;

  //Our setter-methods, which returns it self (the builder object)
        public Builder condensedMilk(int can){this.condensedMilk = can; return this; }
  public Builder chocolateType(String type){this.chocolateType = type; return this; }
  
        public Fudge build() {
   System.out.println("Fudge created!");
            return new Fudge(this);
        }
    }
 //A private constructor for the Fudge class
 //Having this constructor as private make sure that you can't 
 //instance this class in any other way than through the builder class
    private Fudge(Builder builder) {
        
  this.condensedMilk = builder.condensedMilk;
  this.chocolateType = builder.chocolateType;
    }  
}

public class BuilderPatternExample {
  
    public static void main(String args[]) {
  //Create a new fudge with white chocolate
        Fudge WhiteChocolateFudge = new Fudge.Builder()
       .condensedMilk(1)
       .chocolateType("White")
      .build();
    }
}




Enjoy!