Factory Method and Abstract Factory

Sandeep Ahuja
2 min readSep 26, 2020

--

Factory is known for its product manufacturing and assembling of products in wholesome. Here product is an object.

Intent behind the Factory Method:

Most of the initialisers start with init() in swift. They hardly tells you anything specific about the initialization and type of object they are going to provide. Having multiple initializers with different parameters still makes confusion. Lets take an example of Point class.

Here PointFactory is removing the the confusion and using the descriptive names for different initializers.

Now lets take the real existed example of Factory methods in Objective-C Date class.

+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;+ (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs;+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)secs;

All the initialization and allocation is being done by factory methods, returns the complete object.

And NSData offers the following factory methods:

+ (id)dataWithBytes:(const void *)bytes length:(unsigned)length;+ (id)dataWithBytesNoCopy:(void *)bytes length:(unsigned)length;+ (id)dataWithBytesNoCopy:(void *)bytes length:(unsigned)lengthfreeWhenDone:(BOOL)b;+ (id)dataWithContentsOfFile:(NSString *)path;+ (id)dataWithContentsOfURL:(NSURL *)url;+ (id)dataWithContentsOfMappedFile:(NSString *)path;

Most common way we are using Factory methods is to vend singleton object to the callers. These are the class Factory methods that are doing all the initialization and allocation of the object and returning a complete object.

private static let apiInstance = APIInstance()
static func sharedInstance() -> NetworkInstance {
return apiInstance
}

Abstract Factory

Here we create an interface for concrete factory itself. In this way, client works with interface and at run time, client receives the concrete factory object for the use. Here client becomes more decoupled from the received dependency and object creation. Testing becomes easier by injecting mock factory objects.

--

--

Sandeep Ahuja
Sandeep Ahuja

No responses yet