abstract factory design pattern code example
Example 1: abstract factory patrn
public enum BluetoothType
{
CLASSIC_TYPE,
BLE_TYPE
}
public enum WiFiType
{
LOW_BAND,
HIGH_BAND
}
public class ProductPrototypeTWO : ICommunicationBaseFactory
{
private BluetoothType _bluetoothType;
private WiFiType _wifiType;
public ProductPrototypeTWO(BluetoothType bluetoothType, WiFiType wifiType)
{
_bluetoothType = bluetoothType;
_wifiType = wifiType;
}
public IBluetoothCommFactory InitializeBluetoothCommunication()
{
switch (_bluetoothType)
{
case BluetoothType.CLASSIC_TYPE:
return new BluetoothCommunication();
case BluetoothType.BLE_TYPE:
return new BluetoothLowEnergyCommunication();
default:
throw new NotSupportedException("Unknown Bluetooth type");
}
}
public IWifiCommFactory InitializeWiFiCommnucation()
{
switch (_wifiType)
{
case WiFiType.LOW_BAND:
return new WiFiLowBandCommunication();
case WiFiType.HIGH_BAND:
return new WifiHighBandCommunication();
default:
throw new NotSupportedException("Unknown WIFI type");
}
}
}
Example 2: abstract factory patrn
ICommunicationBaseFactory baseFactory = new ProductPrototypeONE();
baseFactory.InitializeBluetoothCommunication();
baseFactory.InitializeWiFiCommnucation();
baseFactory = new ProductPrototypeTWO(BluetoothType.BLE_TYPE, WiFiType.HIGH_BAND);
baseFactory.InitializeBluetoothCommunication();
baseFactory.InitializeWiFiCommnucation();
Example 3: simple factory pattern
enum FanType
{
TableFan,
CeilingFan,
ExhaustFan
}
interface IFan
{
void SwitchOn();
void SwitchOff();
}
class TableFan : IFan {.... }
class CeilingFan : IFan {.... }
class ExhaustFan : IFan {..... }
interface IFanFactory
{
IFan CreateFan(FanType type);
}
class FanFactory : IFanFactory
{
public IFan CreateFan(FanType type)
{
switch (type)
{
case FanType.TableFan:
return new TableFan();
case FanType.CeilingFan:
return new CeilingFan();
case FanType.ExhaustFan:
return new ExhaustFan();
default:
return new TableFan();
}
}
}
//The client code is as follows:
static void Main(string[] args)
{
IFanFactory simpleFactory = new FanFactory();
// Creation of a Fan using Simple Factory
IFan fan = simpleFactory.CreateFan(FanType.TableFan);
// Use created object
fan.SwitchOn();
Console.ReadLine();
}