Interface in F#

module interfaceexample

type IMyFSharpInterface=
abstract member memberWithOneInput : int ->unit
abstract member memberWithTwoInput : int -> float->unit

 

type MyFSharpInterfaceImpl()=
interface IMyFSharpInterface with
member this.memberWithOneInput x = printfn “I am memberWithOneInput implementation”
member this.memberWithTwoInput x y = printfn “I am memberWithTwoInput implementation”

let classobject =new MyFSharpInterfaceImpl()
let a = (classobject:>IMyFSharpInterface).memberWithOneInput 1
let ab = (classobject:>IMyFSharpInterface).memberWithTwoInput 1 2.5

Advertisements

Service Locator example in c#

publicinterfaceICustomer  { string GetCustomerName(); 
 }
  • Implement ICustomer interface.
 classCustomer : ICustomer
    {            publicstring GetCustomerName()          {             return"Customer 1";          	 }      }
  • Create a ServiceLocator as shown below and add the mapping of ICustomer and its real implementation class.
 publicinterfaceIServiceLocator
    {         T GetService<T>();     }      	publicclassServiceLocatorSimple : IServiceLocator
    {    	// map that contains pairs of interfaces and
// references to concrete implementations
privateIDictionary<object, object> services;         	 public ServiceLocatorSimple()          {              	services = newDictionary<object, object>();              // fill the map
this.services.Add(typeof(ICustomer), newCustomer());         }         	 public T GetService<T>()         	 {   try
            {                 	    return (T)services[typeof(T)];               }              catch (KeyNotFoundException)  { thrownewApplicationException("The requested service is not registered"); }          }     }
  • Create a client application to consume it .
 
 staticvoid Main(string[] args)          {           
  IServiceLocator serviceLocator = newServiceLocatorSimple();     
ICustomer customersaervice = serviceLocator.GetService<ICustomer>();  
 Console.WriteLine(customersaervice.GetCustomerName());          }

Now Client application does not know about the concrete implementation. we can easily change the implementation without effecting 
client application.