Differences between Abstract Factory Pattern and Factory Method,confused by one case - abstract-factory

The main difference between a "factory method" and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object. But, sometimes I can't say what it is,for example
class Product{
}
interface Facotory{
public Product create();
}
class FactoryA implements Facotory{
public Product create() {
return null;
}
}
class FactoryB implements Facotory{
public Product create() {
return null;
}
}
Can you tell me it is factory method or abstract factory?Thank you!

IMO, Your current example above is Factory Method.
As you have defined an interface (Factory) with a factory method (create) that allows sub classes (FactoryA and FactoryB) to decide which class to instantiate (Product derived classes).

Related

Variant Generic Interfaces

I have a generic interface, and a class implementing that interface with a concrete type parameter. I also have a generic class using the generic interface as its type constraint, but the type parameter is restricted to be a subclass of a certain base class. I want to instance the generic class with the class implementing that interface but have a problem of converting the class to that interface. The following code illustrates all the classes I mentioned:
The base class:
class DomainBase
{
}
The class used as the type parameter in the interface
class Person : DomainBase
{
}
The generic interface:
public interface IRepository<T> where T : class
{
IEnumerable<T> Fetch();
T Persist(T item);
}
The class implementing the generic interface:
class PersonRepository : IRepository<Person>
{
public IEnumerable<Person> Fetch()
{
...
}
public Person Persist(Person item)
{
...
}
}
The generic class using the generic interface:
class DomainBaseViewModel<Repository>
where Repository : IRepository<DomainBase>, new()
{
private Repository repository = new Repository();
private ObservableCollection<DomainBase> items;
}
However, the following line can't get compiled because PersonRepository is unable to be converted to IRepository<DomainBase>:
var viewModel = new DomainBaseViewModel<PersonRepository>();
Although I can solve this issue by covariance but it disallows the use of the type parameter in parameter lists:
public interface IRepository<out T> where T : class
{
...
T Persist(object item);
}
class PersonRepository : IRepository<Person>
{
public Person Persist(object item)
{
...
}
}
So I have to convert the parameter to Person, which compromises type safety.
Is there a better way to allow covariance and the use of type parameter in parameter lists in this case?
No - the whole point of the restriction on covariance is that it guarantees safety. A PersonRepository isn't an IRepository<DomainBase> because you can't ask it to persist any arbitrary DomainBase object. What would you expect this code to do?
class Product : DomainBase {}
...
IRepository<DomainBase> repository = new PersonRepository();
repository.Persist(new Product());
PersonRepository doesn't know how to persist Product values.
If in some cases you only need the "read" parts of the repository interface, you could always call that out explicitly:
public interface IRepositoryReader<out T>
{
IEnumerable<T> Fetch();
}
public interface IRepository<T> : IRepositoryReader<T>
{
T Persist(T item);
}
Then your DomainBaseViewModel class could be:
class DomainBaseViewModel<TRepository>
where TRepository : IRepositoryReader<DomainBase>, new()
{
private TRepository repository = new TRepository();
private ObservableCollection<DomainBase> items;
}
That doesn't work if you want your DomainBaseViewModel to persist items as well though. In that case, perhaps it should be generic in the type of model as well:
class DomainBaseViewModel<TRepository, TEntity>
where TRepository : IRepository<TEntity>, new()
{
private TRepository repository = new Repository();
private ObservableCollection<TEntity> items;
}
Then:
var viewModel = new DomainBaseViewModel<PersonRepository, Person>();

Class to inherit the constructor of its base class

I would like to know if I can access the constructor of the base class in its derived classes in C#. If yes please let me know how could we make it. Thanks in advance.
You can call the base class constructor as part of the execution of the derived class constructor
public MyBase
{
public MyBase() { }
}
public Derived
{
public Derived() : base() { }
}
When using this pattern, you are said to be using the base class initializer.
For more background, see the base keyword and instance constructors on MSDN.

Factory pattern with CDI depending on runtime parameter

I wanted to implement the factory pattern with CDI. Here we have the business case example:
A client provides a string representing a type. Depending on this type the factory returns an implementation of an interface.
I know that there are a lot of questions flying around concerning factory pattern and CDI. The difference I have here is that I resolve the implementation returned by the factory based on a runtime parameter.
I was thinking of using a producer method but then I can not think of how to inject the resolved implementation into the bean where the implementation is needed since this is a runtime parameter which is not necessarily known at contruction time.
So I thought of the pretty straight forward way of using the Instance class.
Here is the basic implementation :
// the interface. Instances of this class are returned from the factory
public interface Product {
}
// one implementation may be returned by the factory
#ProductType("default")
public class DefaultProduct implements Product {
}
// another implementation may be returned by the factory
#ProductType("myProduct")
public class MyProduct implements Product {
}
// the qualifier annotation
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD, ElementType.TYPE})
public #interface ProductType {
String value();
}
// the Annotation implementation to select
// the correct implementation in the factory
public class ProductTypeLiteral extends AnnotationLiteral<ProductType>
implements ProductType {
private String type;
public ProductTypeLiteral(String type) {
this.type = type;
}
#Override
public String value() {
return type;
}
}
// the factory itself. It is annotated with #Singleton because the
// factory is only needed once
#Singleton
public class Factory {
#Inject
#Any
private Instance<Product> products;
public Product getProduct(String type) {
ProductTypeLiteral literal = new ProductTypeLiteral(type);
Instance<Product> typeProducts = products.select(literal);
return typeProducts.get();
}
}
In my opinion using Instance is very sophisticated.
But this has one major drawback:
Everytime you cal the Instance.get() method you retrieve a new Instance of Product. This may be fine but the Instance instance keeps a reference of the returned instance internally. So as long as the Factory lives and each time the Instance.get() is called the more instances of Product will exist in the memory and never get garbage collected because a reference is still hold in Instance.
I thought of not making the Factory a singleton but that just shifts the problem and does not solve it. And of course it is against the factory pattern.
Another solution I tried was to iterate through the Instance instead of selecting an implementation with the help of the annotation:
#Singleton
public class Factory {
#Inject
#Any
private Instance<Product> products;
public Product getProduct(String type) {
Product product = null;
for(Product eachProduct : products) {
ProductType productType = eachProduct.getClass().
getAnnotation(ProductType.class)
if(productType.value().equals(type) {
product = eachProduct;
break;
}
}
return product;
}
}
Basically this is working. Now each time depending on the given type I retrieve the same instance of Product. That way the memory is not consumed.
But I don't like it to iterate over a collection when I have the possibility to resolve the correct implementations more elegantly.
Do you have any ideas which may solve the problem? Otherwise I may have to keep the iteration solution.
Herein lies your problem. Instance keeps reference to instances you obtain from it using get() because it is responsible for reclaiming them when they go out of scope (i.e. when the injected Instance goes out of scope. But because you made your factory a singleton, it will never go out of scope. So, make your factory a short-lived scope, like #RequestScoped or even #Dependent, that way all the returned instances will be reclaimed properly.
Maybe it can help you:
Create qualifiers:
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
public #interface MyProduct{
}
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
public #interface DefaultProduct{
}
In Factory class:
#Singleton
public class Factory {
public Product getProduct(#MyProduct MyProduct product, #DefaultProduct DefaultProduct defaultProduct) {
//What you wanna do
}
}

derived entity instance in base type is null at initialization time

I have say ClassA entity = new ClassA(){firstname="blah", age=28}
Also class A inherit a ClassB, so in ClassB contructor I want to do something like ClassB()
{ do something with classA entity, but the think is that the entity instance is still null, it goes thru the newing up stage then after the values firstname and age get set, is there a way around this to be able to get the not null instance of the derived class and pass it to the base class? Thankx. Using C# 4.
are you calling ClassA's constructor from ClassB?
public class ClassA
{
}
public class classB
{
public ClassB(): base()
{
//Do something with ClassA
}
}
in client code i have ClassA c = new ClassA(){firstname=""}
in the library it goes like this:
public partial class ClassA: ClassB
{
}
public class classB
{
public ClassB()
{
AddValidation(..);//here i want to acces the instance of entity ClassA that was populated in client code.
}
}

Class design according to IoC and Abstract Factory pattern

Which is the correct way of providing values to a abstract factory method?
Eg.
interface IFactory
{
ISomething Create(int runTimeValue);
}
class Factory : IFactory
{
public ISomething Create(int runTimeValue)
{
return new Something(repository, runTimeValue);
}
}
In the example the repository is injected via the constructor when factory is created but I could instead move the repository to the IFactory interface
interface IFactory
{
ISomething Create(IRepository repository, int runTimeValue);
}
class Factory : IFactory
{
public ISomething Create(IRepository repository, int runTimeValue)
{
return new Something(repository, runTimeValue);
}
}
What is considered "correct" way of doing this?
How should one reason when designing an abstract factory?
Abstract Factory pattern should be used in cases when the objects returned by the factory need to be "initialized" differently in such a way that only the factory knows how to do it. So different implementations of ISomething will be "initialized" or created differently and only their respective Factory implementations know how to do it.
In your case you have to ask yourself:
Do all implementations of ISomethings need the IRepository as well as runtimeValue?. In that case you can just use the factory pattern.
Use Abstract Factory in such a scenario: (Something and SomeOtherthing are created differently)
interface IFactory {
ISomething Create(int runTimeValue);
}
class Factory : IFactory {
public ISomething Create(int runTimeValue) {
return new Something(repository, runTimeValue);
}
}
class OFactory : IFactory {
public ISomething Create(int runTimeValue) {
// constructor takes different parameters
SomeOtherthing thing = new SomeOtherthing("someValue", runtimeValue);
thing.SetCustomRepository(new OtherRepositoryImpl());
return thing;
}
}
I'd say be consistent. If your repository is injected everywhere else that it is used, it would make sense to inject it into the factory's constructor rather than making it a part of the interface.

Resources