Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created June 18, 2016 13:31
Show Gist options
  • Save mitulmanish/50e9949e3b94a9c1b5a8d92be909f0fd to your computer and use it in GitHub Desktop.
Save mitulmanish/50e9949e3b94a9c1b5a8d92be909f0fd to your computer and use it in GitHub Desktop.
Factory Pattern implemented in Java
package com.company;
enum Country
{
UnitedStates, Spain, Greece, UK
}
interface Currency {
String symbol();
String code();
}
class Euro implements Currency {
@Override
public String symbol() {
return "E";
}
@Override
public String code() {
return "EUR";
}
}
class UnitedStatesDollar implements Currency {
@Override
public String symbol() {
return "$";
}
@Override
public String code() {
return "USD";
}
}
class CurrencyFactory {
static Currency currencyForCountry(Country country) {
switch (country) {
case Spain:
return new Euro();
case Greece:
return new Euro();
case UnitedStates:
return new UnitedStatesDollar();
default:
return null;
}
}
}
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(CurrencyFactory.currencyForCountry(Country.Greece).code());
System.out.println(CurrencyFactory.currencyForCountry(Country.UnitedStates).symbol());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment