Tuesday, December 31, 2013

atomic vs nonatomic in iOS / atomicity in iOS / what is atomic in iOS / what is nonatomic in iOS / what is @atomic in iOS / what is @nonatomic in iOS/

Atomicity: you have likely seen “nonatomic” in property declarations numerous times. When you declare a property as atomic, you usually wrap it in a @synchronized block to make it thread safe. Of course, this approach does add some extra overhead. To give you an idea, here is a rough implementation of an atomic property:
// If you declare a property as atomic ...
@property (atomic, retain) NSString *myString;

// ... a rough implementation that the system generates automatically,
// looks like this:
- (NSString *)myString {
    @synchronized (self) {
        return [[myString retain] autorelease];
    }

}

In this code, “retain” and “autorelease” calls are used as the returned value is being accessed from multiple threads, and you do not want the object to get deallocated between calls.

Therefore, you retain the value first, and then put it in an autorelease pool. You can read more in Apple’s documentation about Thread Safety. This is worth knowing, if only for the reason that most iOS programmers never bother to find this out. Protip: this makes a great job interview question! :]

Most of the UIKit properties are not thread-safe. To find out whether a class is thread-safe or not, take a look at the API documentation. If the API documentation does not say anything about thread-safety, then you should assume that the class is not thread-safe.

As a general rule, if you are executing on a secondary thread and you must do something to a UIKit object, use performSelectorOnMainThread.

NSAutoreleasePool in iOS / why NSAutoreleasePool needed ?

NSAutoreleasePool:-

The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.

Why NSAutoreleasePool is needed?:- 

To minimize the peak memory footprint. Use in block of code when you feel that there is lots of memory creation happened.

If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

USage:-


Important: If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:

Without ARC:- 
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

// Code benefitting from a local autorelease pool.

[pool release];

With ARC :-
you would write:


@autoreleasepool {

    // Code benefitting from a local autorelease pool.

}

@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.

More About NSAutoreleasePool

In a reference counted environment, Cocoa expects there to be an autorelease pool always available. If a pool is not available, autoreleased objects do not get released and you leak memory.
The Application Kit creates an autorelease pool on the main thread at the beginning of every cycle of the event loop, and drains it at the end, thereby releasing any autoreleased objects generated while processing an event. If you use the Application Kit, you therefore typically don’t have to create your own pools. If your application creates a lot of temporary autoreleased objects within the event loop, however, it may be beneficial to create “local” autorelease pools to help to minimize the peak memory footprint.

Since you cannot retain an autorelease pool (or autorelease it—see retain andautorelease), draining a pool ultimately has the effect of deallocating it.

Threads and NSAutoreleasePool

Each thread (including the main thread) maintains its own stack of NSAutoreleasePool objects (see “Threads”). As new pools are created, they get added to the top of the stack. When pools are deallocated, they are removed from the stack. Autoreleased objects are placed into the top autorelease pool for the current thread. When a thread terminates, it automatically drains all of the autorelease pools associated with itself.

Thursday, December 19, 2013

Bridge pattern - Structural Design Pattern

Bridge Pattern

Bridge Pattern
Ref:-

Its a structural design pattern.
Just like how printers work with computers. If we have a USB cable (bridge), then we can connect any printer to any computer to start printing. It really doesn't matter if it's a laser printer or a color printer, either Windows PC or Mac.
 This pattern decouples implementation class and abstract class by providing a bridge structure between them.
This pattern involves an interface which acts as a bridge  , which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other. 

Implementation

We've an interface DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle.


#### bridge interface acting as bridge between Shape and colors
public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}

public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}

public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}

public abstract class Shape {
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();
}

public class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}

public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

      redCircle.draw();
      greenCircle.draw();
   }
}

Wednesday, December 18, 2013

Adapter pattern - Structurel pattern

Adapter Pattern

Adapter design pattern allows you to make an existing class work with other existing class libraries without changing the code of the existing class.
Maximum times we needed that methods of the existing class should work with other existing class to work .  Example :- Say we have one class its function is doing one work and we  have to add some functionality by using existing library but they are not compatiable.
To solve this problem we have to create another class Adapter  that inherits from the existing class while implementing the interface of the existing library(normally library gives interface to acces its functionality). The end result is that the Adapter can call the method of the existing class (since theAdapter inherits from the existing class) and can work in the existing library (since the Adapter implements the interface of the existing library).

A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugins the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

Below is the UML of the Adapter Design Pattern:

  • The Adaptee is the existing class.
  • The IInterface is the interface defined in the existing library.
  • The Adapter is the class that you create, it is inherited from the Adaptee class and it implements theIInterface interface. Notice that it can call the OperationA method(inherited from the Adaptee) inside its OperationB method (implemented by the IInterface).
Example:-an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files.

Implementation:- 



We want to make AudioPlayer to play other formats as well.
We're having ( library )another interface AdvancedMediaPlayer and concrete classes implementing theAdvancedMediaPlayer interface.These classes can play vlc and mp4 format files.
we've created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayerobjects to play the required format.
AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will useAudioPlayer class to play various formats.



#### Library implemented as
public interface AdvancedMediaPlayer {
   public void playVlc(String fileName);
   public void playMp4(String fileName);
}
public class VlcPlayer implements AdvancedMediaPlayer{
   @Override
   public void playVlc(String fileName) {
      System.out.println("Playing vlc file. Name: "+ fileName);
   }

   @Override
   public void playMp4(String fileName) {
      //do nothing
   }
}

public class Mp4Player implements AdvancedMediaPlayer{

   @Override
   public void playVlc(String fileName) {
      //do nothing
   }

   @Override
   public void playMp4(String fileName) {
      System.out.println("Playing mp4 file. Name: "+ fileName);
   }
}

##### Adapter class 
public class MediaAdapter implements MediaPlayer {

   AdvancedMediaPlayer advancedMusicPlayer; // not support multiple inheritance so omposed

   public MediaAdapter(String audioType){
      if(audioType.equalsIgnoreCase("vlc") ){
         advancedMusicPlayer = new VlcPlayer();
      } else if (audioType.equalsIgnoreCase("mp4")){
         advancedMusicPlayer = new Mp4Player();
      }
   }

   @Override
   public void play(String audioType, String fileName) {
      if(audioType.equalsIgnoreCase("vlc")){
         advancedMusicPlayer.playVlc(fileName);
      }else if(audioType.equalsIgnoreCase("mp4")){
         advancedMusicPlayer.playMp4(fileName);
      }
   }
}
#### existing class
public interface MediaPlayer {
   public void play(String audioType, String fileName);
}
public class AudioPlayer implements MediaPlayer {
   MediaAdapter mediaAdapter; 

   @Override
   public void play(String audioType, String fileName) {

      //inbuilt support to play mp3 music files
      if(audioType.equalsIgnoreCase("mp3")){
         System.out.println("Playing mp3 file. Name: "+ fileName);
      } 
      //mediaAdapter is providing support to play other file formats
      else if(audioType.equalsIgnoreCase("vlc") 
         || audioType.equalsIgnoreCase("mp4")){
         mediaAdapter = new MediaAdapter(audioType);
         mediaAdapter.play(audioType, fileName);
      }
      else{
         System.out.println("Invalid media. "+
            audioType + " format not supported");
      }
   }   
}


public class AdapterPatternDemo {
   public static void main(String[] args) {
      AudioPlayer audioPlayer = new AudioPlayer();

      audioPlayer.play("mp3", "beyond the horizon.mp3");
      audioPlayer.play("mp4", "alone.mp4");
      audioPlayer.play("vlc", "far far away.vlc");
      audioPlayer.play("avi", "mind me.avi");
   }
}


Prototype pattern - Creational Design Pattern

Prototype Pattern

Its a creational design pattern. Its normally used to create duplicate objects.  This pattern is used normally when the creation of object is costly.  Example:- Object created and have lots of expensive operation like sql query etc  When next time we want same kind object we will return its clone , It reduces expensive operation of sql query. It save building/ instantiation process for the object. There is no limit on copying existing object.

ref :-http://www.tutorialspoint.com/design_pattern/prototype_pattern.htm















Implementation:-

As mentioned in UML ShapeCache is used to keep the object of the Shape in cache i.e in HashMap and will be responsible to return their clone on requested.


Java Code:-

#####Shape classes
public abstract class Shape implements Cloneable {
   
   private String id;
   protected String type;
   
   abstract void draw();
   
   public String getType(){
      return type;
   }
   
   public String getId() {
      return id;
   }
   
   public void setId(String id) {
      this.id = id;
   }
   
   public Object clone() {
      Object clone = null;
      try {
         clone = super.clone();
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      return clone;
   }
}

public class Rectangle extends Shape {

   public Rectangle(){
     type = "Rectangle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square extends Shape {

   public Square(){
     type = "Square";
   }

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

public class Circle extends Shape {

   public Circle(){
     type = "Circle";
   }

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}


#### cache/ clone class


import java.util.Hashtable;

public class ShapeCache {
   private static Hashtable<String, Shape> shapeMap 
      = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}


#####main func

import java.util.Hashtable;

public class ShapeCache {
   private static Hashtable<String, Shape> shapeMap 
      = new Hashtable<String, Shape>();

   public static Shape getShape(String shapeId) {
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
   }

   // for each shape run database query and create shape
   // shapeMap.put(shapeKey, shape);
   // for example, we are adding three shapes
   public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);

      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);

      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(),rectangle);
   }
}

Builder Design Pattern - Creational Design Pattern


Builder Pattern

Ref:- http://www.tutorialspoint.com/design_pattern/builder_pattern.htm

Its creational design pattern.
Builder pattern builds a complex object using simple objects and using step by step approach. The builder is independent of other objects.

Example:-
This pattern is used by fast food restaurants to construct children's meals. Children's meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the children's meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants.





Code in JAVA
#### packaging
public interface Packing {
   public String pack();
}


public class Wrapper implements Packing {

   @Override
   public String pack() {
      return "Wrapper";
   }
}


public class Bottle implements Packing {

   @Override
   public String pack() {
      return "Bottle";
   }
}

###### item
public interface Item {
   public String name();
   public Packing packing();
   public float price();
}
public abstract class Burger implements Item {

   @Override
   public Packing packing() {
      return new Wrapper();
   }

   @Override
   public abstract float price();
}


public abstract class ColdDrink implements Item {

@Override
public Packing packing() {
       return new Bottle();
}

@Override
public abstract float price();
}


public class VegBurger extends Burger {

   @Override
   public float price() {
      return 25.0f;
   }

   @Override
   public String name() {
      return "Veg Burger";
   }
}



public class ChickenBurger extends Burger {

   @Override
   public float price() {
      return 50.5f;
   }

   @Override
   public String name() {
      return "Chicken Burger";
   }
}


public class Coke extends ColdDrink {

   @Override
   public float price() {
      return 30.0f;
   }

   @Override
   public String name() {
      return "Coke";
   }
}


public class Pepsi extends ColdDrink {

   @Override
   public float price() {
      return 35.0f;
   }

   @Override
   public String name() {
      return "Pepsi";
   }
}

#### Meal main class which object to build

import java.util.ArrayList;
import java.util.List;

public class Meal {
   private List<Item> items = new ArrayList<Item>();

   public void addItem(Item item){
      items.add(item);
   }

   public float getCost(){
      float cost = 0.0f;
      for (Item item : items) {
         cost += item.price();
      }
      return cost;
   }

   public void showItems(){
      for (Item item : items) {
         System.out.print("Item : "+item.name());
         System.out.print(", Packing : "+item.packing().pack());
         System.out.println(", Price : "+item.price());
      }
   }
}



public class MealBuilder {

   public Meal prepareVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
   }   

   public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
   }
}


public class BuilderPatternDemo {
   public static void main(String[] args) {
      MealBuilder mealBuilder = new MealBuilder();

      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " +vegMeal.getCost());

      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " +nonVegMeal.getCost());
   }
}




Singleton Design Pattern - Creational Design Pattern

Singleton Design Pattern

Its creational design pattern.  Singleton pattern is to ensure that a class has only one instance and provides global point of access it.

Implementation
Singleton class have its constructor as private and have static instance of itself. Class provides a static method to get its static instance to outside world.
A simple UML of the GoF singleton is shown below:








Code for Singleton


class MySingleton
{
    private MySingleton() { }

    public static MySingleton CreateInstance()
    {
        if (singleton == null)
        {
            lock (typeof(MySingleton))
            {
                if (singleton == null)
                    singleton = new MySingleton();
            }
        }
        return singleton;
    }
    private static volatile MySingleton singleton = null;
}




About

Powered by Blogger.