---
# System prepended metadata

title: 'Factory Method & Abstract Method:'
tags: [Design Pattern]

---

---
tags: Design Pattern
---

# Factory Method & Abstract Method:

![](https://i.imgur.com/hClsK57.png)

The point is to encapsulate the constructor so that people cannot operate at will.


---

A little explanation of the interface and abstract differences before entering the code

<font color="#f00">interface: </font>
 Once any class inherits the interface, it will be required to clearly define what all the methods in the interface should do within the class, otherwise an error will be reported.
 ```cpp
interface animals
{
    void barking();
}

class cat : Ianimals
{
    public void barking()
    {
        Console.WriteLine("喵喵喵")
    }
}
```
 
 <font color="#f00">abstract class: </font>
 
The methods in the abstract class can be added with words such as protected and public, and no error will be reported at all, which means that methods that can be used internally should be allowed in the abstract class.
```cpp=
abstract class BaseClass   
{
    protected int _x = 100;
    protected int _y = 150;
    public abstract void AbstractMethod();   
    private void Test(){ }
    public abstract int X    { get; }
    public abstract int Y    { get; }
}

class DerivedClass : BaseClass
{
    public override void AbstractMethod()
    {
        _x++;
        _y++;
    }

    public override int X   
    {
        get
        {
            return _x + 10;
        }
    }

    public override int Y  
    {
        get
        {
            return _y + 10;
        }
    }
}
```

## Factory Method
```cpp=
public abstract class PizzaStore{

   public Pizza orderPizza(String aType){

      Pizza pizza = createPizza(aType);

      pizza.prepare();

      pizza.bake();

      pizza.cut();

      pizza.box();

      return pizza;

   }

   public abstract Pizza createPizza();

}
```

## Abstract Method
```cpp=
public interface PizzaIngredientFactory{

    public Dough createDough();

    public Sauce createSauce();

    public Cheese createCheese();

    public Veggies[]  createVeggies();

...

}

public class TWPizzaIngredientFacotry implements PizzaIngredientFactory

{

    public Dough createDough(){

       return new thickDough();  //為什麼台灣的pizza餅皮都要那麼厚呢？

    }

    public Sauce createSauce(){

         return new MarinaraSauce();//這邊就直接抄書上了

    }

    public Cheese createCheese(){  //台灣不產cheese，所以可以用各種cheese

        return new cheese();

    }

    .......

}

public class Pizza{

    PizzaIngredientFactory  mIngredientFactory;

   public Pizza(PizzaIngredientFactory  aIngredientFactory){

         mIngredientFactory  = aIngredientFactory;

   }

 

    ....

}
```


reference: 

1. https://ccas.pixnet.net/blog/post/36195321

2. https://scriptjerks.blogspot.com/2012/06/c.html
3. https://dotblogs.com.tw/supergary/2020/09/30/InterfaceAndAbstract
