Вопрос по – В чем принципиальная разница между фабричными и абстрактными фабричными моделями? [закрыто]

457

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededTengiz's answerError: User Rate Limit Exceeded Dave Schweisguth
Error: User Rate Limit ExceededcreateThing()Error: User Rate Limit ExceededgetFactory().createThing() ) David James
Error: User Rate Limit ExceededDifferences between Abstract Factory Pattern and Factory MethodError: User Rate Limit Exceeded KurzedMetal

Ваш Ответ

19   ответов
3

Extending John Feminella answer:

Apple, Banana, CherryError: User Rate Limit ExceededFruitFactoryError: User Rate Limit ExceededCreateError: User Rate Limit ExceededFactoryError: User Rate Limit Exceeded

Error: User Rate Limit ExceededCreateError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit Exceeded

public class Apple implements Fruit, FruitFactory {
    public Fruit Create() {
        // Apple creation logic goes here
    }
}

public class Banana implements Fruit, FruitFactory {
    public Fruit Create() {
        // Banana creation logic goes here
    }
}

public class Cherry implements Fruit, FruitFactory {
    public Fruit Create() {
        // Cherry creation logic goes here
    }
}

public class SpecialSalad implements Salad, SaladFactory {
    public static Salad Create(FruitFactory[] fruits) {
        // loop through the factory and create the fruits.
        // then you're ready to cut and slice your fruits 
        // to create your special salad.
    }
}
16
//Abstract factory - Provides interface to create factory of related products
interface PizzaIngredientsFactory{    
   public Dough createDough(); //Will return you family of Dough
   public Clam createClam();   //Will return you family of Clam
   public Sauce createSauce(); //Will return you family of Sauce
}

class NYPizzaIngredientsFactory implements PizzaIngredientsFactory{

   @Override
   public Dough createDough(){
      //create the concrete dough instance that NY uses
      return doughInstance;
   }

   //override other methods
} 

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededPizzaIngredientsFactoryError: User Rate Limit Exceededabstract factoryError: User Rate Limit Exceeded

Error: User Rate Limit ExceededFactory methodError: User Rate Limit ExceededcreateDough()Error: User Rate Limit ExceededNYPizzaIngredientsFactoryError: User Rate Limit Exceeded

Factory Method

Provides instance of concrete implementation

Error: User Rate Limit Exceeded
- createDough()Error: User Rate Limit Exceeded

Abstract Factory

Provides interface to create family of related objects

Error: User Rate Limit Exceeded
- PizzaIngredientsFactoryError: User Rate Limit ExceededDough, Clams, SauceError: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

3

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceededfactory pattern.

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

1

Error: User Rate Limit Exceeded

393

Error: User Rate Limit ExceededApple, Banana, CherryError: User Rate Limit ExceededIFruit.

Error: User Rate Limit ExceededIFruitFactoryError: User Rate Limit ExceededIJuiceFactoryError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Завод, который производит фабрики. Нам нужно идти глубже ...
@joaquin Например, когда вам нужно иметь фабрику IFruitFactory. И, как я уже упоминал, это совершенно неверно, и это просто результат путаницы в шаблонах. Мой ответ ниже проясняет: есть шаблон «Абстрактная фабрика», затем шаблон «Метод фабрики», и есть люди, которые думают, что Абстрактная фабрика означает фабрику других фабрик. Фабрика - это просто общий термин, используемый для обозначения любого из существующих шаблонов. Смотрите мой ответ ниже для более подробной информации, если это необходимо.
Этот ответ просто неправильно! Согласно этомуGoF bookError: User Rate Limit Exceededabstract factoryError: User Rate Limit Exceededcreating фабрики. Пожалуйста, удалите этот ответ, он вводит в заблуждение и сбивает с толку людей!
@ SPI Я думаю, вы меня не так поняли; Сама Фабрика не нуждается в реализацииIFruit - это создает вещи, которые реализуютIFruitError: User Rate Limit ExceededneedError: User Rate Limit Exceeded
38

Factory method:Error: User Rate Limit Exceeded

Abstract factory:Error: User Rate Limit Exceededother factoriesError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
42

The Abstract Factory Pattern

  • Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

  • The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation.

  • Actually, the delegated object frequently uses factory methods to perform the instantiation!

Factory pattern

  • Factory patterns are examples of creational patterns

  • Creational patterns abstract the object instantiation process. They hide how objects are created and help make the overall system independent of how its objects are created and composed.

  • Class creational patterns focus on the use of inheritance to decide the object to be instantiated Factory Method

  • Object creational patterns focus on the delegation of the instantiation to another object Abstract Factory

Error: User Rate Limit ExceededFactory vs Abstract Factory

Error: User Rate Limit Exceeded
2

Error: User Rate Limit ExceededFactory MethodError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit ExceededFactoryError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit Exceeded

Error: User Rate Limit ExceededFactory MethodError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit Exceeded

Error: User Rate Limit ExceededAbstract FactoryError: User Rate Limit ExceededFactory Method.

140

Source for this information taken from: http://java.dzone.com/news/intro-design-patterns-abstract

Abstract Factory vs. Factory Method

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

How to implement

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

When to Use the Factory Method Pattern

Error: User Rate Limit Exceeded

When to Use the Abstract Factory Pattern

Error: User Rate Limit Exceeded

Examples:

Abstract Factory Example 1

Error: User Rate Limit Exceeded

Abstract Factory Example 2:

Error: User Rate Limit Exceeded

Factory Method Example:

Error: User Rate Limit Exceeded

Можно ли определить в коде, какой из этих двух шаблонов был использован?
Пример кода @sourcemaking.com/design_patterns/abstract_factory
пример композиции: открытый класс Client {AbstractProduct product; АннотацияПродуктыАксессуары для аксессуаров; публичный клиент (фабрика AbstractFactory,) {AbstractProduct product = factory.createProduct (); } public void run () {product.print (); аксессуары = product.getAccessories (); }}
то же самое и здесь, было бы гораздо яснее, если бы подходы к составлению и наследованию были показаны на кратком примере (исходный код).
Спасибо за объяснение абстрактной фабрики и фабричного метода. Я не понял, где мы используем композицию в абстрактной фабрике для создания объектов и где мы используем наследование в фабричном методе. Будет очень полезно, если вы опубликуете некоторый код для их объяснения. Большое спасибо. жду вашего кода. Еще раз спасибо.
34

Basic difference:

Factory:Error: User Rate Limit Exceeded

Factory MethodError: User Rate Limit Exceeded

Abstract FactoryError: User Rate Limit Exceeded

AbstractFactoryError: User Rate Limit ExceededFactory methodError: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

FactoryError: User Rate Limit Exceeded

enter image description here

Example: StaticFactory

 public class ShapeFactory {

   //use getShape method to get object of type shape 
   public static Shape getShape(String shapeType){
      if(shapeType == null){
         return null;
      }     
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();

      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();

      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }

      return null;
   }
}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

When to use:Error: User Rate Limit Exceeded

Factory MethodError: User Rate Limit Exceeded

enter image description here

When to use:Error: User Rate Limit Exceeded

Abstract FactoryError: User Rate Limit ExceededError: User Rate Limit Exceeded

enter image description here

When to use:Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Differences:

  1. Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype
  2. Designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward other creational patterns (more flexible, more complex) where more flexibility is needed.
  3. Factory Methods are usually called within Template Methods.

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
1

Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

21

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded

Хорошие сценарии AbstractFactory, но вы действительно не ответили на вопрос, в чем разница между фабрикой и абстрактной фабрикой.
2

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

public interface IFactory{
  void VehicleType(string n);
 }

 public class Scooter : IFactory{
  public void VehicleType(string n){
   Console.WriteLine("Vehicle type: " + n);
  }
 }

 public class Bike : IFactory{
  public void VehicleType(string n) {
  Console.WriteLine("Vehicle type: " + n);
  }
 }

 public interface IVehicleFactory{
  IFactory GetVehicleType(string Vehicle);
 }

 public class ConcreteVehicleFactory : IVehicleFactory{
 public IFactory GetVehicleType(string Vehicle){
   switch (Vehicle){
    case "Scooter":
     return new Scooter();
    case "Bike":
     return new Bike();
    default:
    return new Scooter();
  }
 }

 class Program{
  static void Main(string[] args){
   IVehicleFactory factory = new ConcreteVehicleFactory();
   IFactory scooter = factory.GetVehicleType("Scooter");
   scooter.VehicleType("Scooter");

   IFactory bike = factory.GetVehicleType("Bike");
   bike.VehicleType("Bike");

   Console.ReadKey();
 }
}

Error: User Rate Limit Exceeded

interface IVehicleFactory{
 IBike GetBike();
 IScooter GetScooter();
}

class HondaFactory : IVehicleFactory{
     public IBike GetBike(){
            return new FZS();
     }
     public IScooter GetScooter(){
            return new FZscooter();
     }
 }
class HeroFactory: IVehicleFactory{
      public IBike GetBike(){
            return new Pulsur();
     }
      public IScooter GetScooter(){
            return new PulsurScooter();
     }
}

interface IBike
    {
        string Name();
    }
interface IScooter
    {
        string Name();
    }

class FZS:IBike{
   public string Name(){
     return "FZS";
   }
}
class Pulsur:IBike{
   public string Name(){
     return "Pulsur";
   }
}

class FZscooter:IScooter {
  public string Name(){
     return "FZscooter";
   }
}

class PulsurScooter:IScooter{
  public string Name(){
     return "PulsurScooter";
   }
}

enum MANUFACTURERS
{
    HONDA,
    HERO
}

class VehicleTypeCheck{
        IBike bike;
        IScooter scooter;
        IVehicleFactory factory;
        MANUFACTURERS manu;

        public VehicleTypeCheck(MANUFACTURERS m){
            manu = m;
        }

        public void CheckProducts()
        {
            switch (manu){
                case MANUFACTURERS.HONDA:
                    factory = new HondaFactory();
                    break;
                case MANUFACTURERS.HERO:
                    factory = new HeroFactory();
                    break;
            }

      Console.WriteLine("Bike: " + factory.GetBike().Name() + "\nScooter: " +      factory.GetScooter().Name());
        }
  }

class Program
    {
        static void Main(string[] args)
        {
            VehicleTypeCheck chk = new VehicleTypeCheck(MANUFACTURERS.HONDA);
            chk.CheckProducts();

            chk= new VehicleTypeCheck(MANUFACTURERS.HERO);
            chk.CheckProducts();

            Console.Read();
        }
    }
3

Error: User Rate Limit ExceededStackOverflow, tutorialspoint.com, programmers.stackexchange.comError: User Rate Limit ExceededCodeProject.com.


Factory MethodError: User Rate Limit ExceededFactoryError: User Rate Limit ExceededInterfaceError: User Rate Limit ExceededShapeError: User Rate Limit ExceededCircleError: User Rate Limit ExceededSquareError: User Rate Limit ExceededTypeError: User Rate Limit ExceededShapeError: User Rate Limit Exceeded


Abstract FactoryError: User Rate Limit ExceededColorError: User Rate Limit ExceededRedError: User Rate Limit ExceededYellowError: User Rate Limit ExceededShapeColorFactoryError: User Rate Limit ExceededRedCircleFactoryError: User Rate Limit ExceededYellowSquareFactoryError: User Rate Limit Exceeded

interface ShapeColorFactory
{
    public Shape getShape();
    public Color getColor();
}

class RedCircleFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Circle();
    }

    @Override
    public Color getColor() {
        return new Red();
    }
}
class YellowSquareFactory implements ShapeColorFactory
{
    @Override
    public Shape getShape() {
        return new Square();
    }

    @Override
    public Color getColor() {
        return new Yellow();
    }
} 

Error: User Rate Limit ExceededFactoryMethodError: User Rate Limit ExceededAbstractFactory. Factory MethodError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit Exceededfactory of factoryError: User Rate Limit ExceededAbstract FactoryError: User Rate Limit Exceeded


Error: User Rate Limit Exceeded

36

Error: User Rate Limit Exceeded

enter image description here

5

Error: User Rate Limit Exceeded

Abstract factory is a factory of factories!

Error: User Rate Limit ExceededLemon, OrangeError: User Rate Limit ExceededIFruitError: User Rate Limit ExceededCitricFruitFactory.

Error: User Rate Limit ExceededCitricFruitFactoryError: User Rate Limit ExceededStrawberryError: User Rate Limit Exceeded

Error: User Rate Limit ExceededRedFruitFactoryError: User Rate Limit ExceededStrawberry, RaspberryError: User Rate Limit Exceeded

Like John Feminella said: "With the Abstract Factory pattern, you produce implementations of a particular Factory interface -- e.g., IFruitFactory. Each of those knows how to create different kinds of fruit."

Error: User Rate Limit ExceededIFruitFactoryError: User Rate Limit ExceededCitricFruitFactoryError: User Rate Limit ExceededRedFruitFactory!

19

Error: User Rate Limit ExceededincorrectError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

  • Some people use it as an alias (shortcut) for "Abstract Factory".
  • Some people use it as an alias (shortcut) for "Factory Method".
  • Some people use it as a more general name for all factory/creational patterns. E.g. both "Abstract Factory" and "Factory Method" are Factories.

Error: User Rate Limit ExceededunfortunatelyError: User Rate Limit Exceeded

Product implements IProduct, which is created by Factory, which implements IFactory, which is created by AbstractFactory.

Error: User Rate Limit Exceeded

AbstractFactory implements IAbstractFactory, which is created by... AbstractAbstractFactory???

Error: User Rate Limit Exceeded

-

P.S.Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Как можно отличить AbstractFactory, которая создает другие AbstractFactory, от AbstractFactory, которая создает конкретные объекты? GenericAbstractFactory? Или AbstractFactoryFactory?
В шаблонах дизайна такого нет. Оба они являются экземплярами шаблона AbstractFactory. Итак, одна AbstractFactory создает конкретные объекты, а другая AbstractFactory создает фабрики (которые снова являются AbstractFactory).
Error: User Rate Limit Exceeded
96

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

[Update according to the comments]
Error: User Rate Limit ExceededError: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededGoF book,abstract factory является фабричным объектом, который реализует фабричный интерфейс, так что конкретная фабрика может быть заменена на другой подкласс. Это не имеет ничего общего сcreatingError: User Rate Limit Exceeded
Я думаю, это было бы правильно, но это также упустило бы смысл :). Не аналогичным примером может быть FileFactory, который имеет такие методы, как CreateBitmapFile () или CreateTextFile (). Теперь вы передадите ссылку на эту фабрику в какой-то сервис. Но что произойдет, если вы захотите проверить свой сервис? Вам придется создать интерфейс IFileFactory, чтобы запретить доступ к файловой системе. Теперь, в реальном мире, у вас, вероятно, будет структура DI / IoC, которая будет создавать экземпляры IFileFactories в зависимости от ваших потребностей. В этом случае структура IoC будет служить абстрактной фабрикой.
Error: User Rate Limit Exceededcan быть фабрикой фабрик, она не обязательно должна быть таковой. Это производитель сопутствующих товаров.
Если я правильно понимаю, этот ответ подразумевает, что Абстрактная фабрика всегдаproducesError: User Rate Limit ExceedednotError: User Rate Limit Exceededneed not beError: User Rate Limit Exceeded
1

Error: User Rate Limit Exceeded

  interface Something{}

  interface OneWhoCanProvideSomething {
     Something getSomething();
  }

  interface OneWhoCanProvideCreatorsOfSomething{
     OneWhoCanProvideSomething getCreator();
  }


public class AbstractFactoryExample {

    public static void main(String[] args) {
        //I need something
        //Let's create one
        Something something = new Something() {};

        //Or ask someone (FACTORY pattern)
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
        OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;

        //Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
        OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;

        //Same thing, but you don't need to write you own interfaces
        Supplier<Something> supplierOfSomething = () -> null;
        Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
    }

}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Note that you can always get away with Factory pattern by combining two conditions together (which slightly increases code complexity, and coupling), I guess that's why we rarely see real life use cases of Abstract Factory pattern.

Похожие вопросы