+1
Under review

Interface vs Factory method

Chan Sophea Kaing 1 year ago updated 1 year ago 2

Hello, going through factory method I still dont understand why we have to go through all the hustle of implementing it when we can just use interface alone and make a direct construction from the class that implement it. For example:

interface User {
getName: string;
getToken: string;
}

class Vendor implements User {
  getName(){
    return 'some name';
 }

  getToken() {
   return 'some token';
  }
}

class Buyer implements User {
getName(){
return 'some name';
}

getToken() {
return 'some token';
}
}

const vendor = new Vendor();
const buyer = new Buyer();

Now if there are more type of user, we can simply just use interface and make a direct construction from its class. Why is a factory method a better choice in this case ? Sorry I might have not understood it clear.
+1
Under review

Avoiding the direct construction of products on the client code is a whole point of the pattern. If you don't have this problem, you don't need to apply the pattern. If you can get away with a simple interface, then do it—the simpler the code, the better.

thank you for your answer :)