Kody źródłowe/Metoda wytwórcza (wzorzec projektowy)

Metoda wytwórcza (wzorzec projektowy) • Kod źródłowy
Metoda wytwórcza (wzorzec projektowy)
Kod źródłowy
Kody źródłowe programów stosujących wzorzec projektowy metody wytwórczej
Wikipedia
Zobacz w Wikipedii hasło Metoda wytwórcza


Pizza example:

abstract class Pizza {
    public abstract double getPrice();
}

class HamAndMushroomPizza extends Pizza {
    private double price = 8.5;

    public double getPrice() {
        return price;
    }
}

class DeluxePizza extends Pizza {
    private double price = 10.5;

    public double getPrice() {
        return price;
    }
}

class HawaiianPizza extends Pizza {
    private double price = 11.5;

    public double getPrice() {
        return price;
    }
}

class PizzaFactory {
    public enum PizzaType {
        HamMushroom,
        Deluxe,
        Hawaiian
    }

    public static Pizza createPizza(PizzaType pizzaType) {
        switch (pizzaType) {
            case HamMushroom:
                return new HamAndMushroomPizza();
            case Deluxe:
                return new DeluxePizza();
            case Hawaiian:
                return new HawaiianPizza();
        }
        throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
    }
}

class PizzaLover {
    /**
     * Create all available pizzas and print their prices
     */
    public static void main (String args[]) {
        for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) {
            System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
        }
    }
}
trait Pizza {
    fn get_price(&self) -> f32;
}

struct HamAndMushroomPizza;
impl Pizza for HamAndMushroomPizza {
    fn get_price(&self) -> f32 {
        8.5
    }
}

struct DeluxePizza;
impl Pizza for DeluxePizza {
    fn get_price(&self) -> f32 {
        10.5
    }
}

struct HawaiianPizza;
impl Pizza for HawaiianPizza {
    fn get_price(&self) -> f32 {
        11.5
    }
}

enum PizzaType {
    HamAndMushroom,
    Deluxe,
    Hawaiian,
}

fn create_pizza(pizza_type: PizzaType) -> Box<dyn Pizza> {
    match pizza_type {
        PizzaType::HamAndMushroom => Box::new(HamAndMushroomPizza),
        PizzaType::Deluxe => Box::new(DeluxePizza),
        PizzaType::Hawaiian => Box::new(HawaiianPizza),
    }
}

fn main() {
    let pizza = create_pizza(PizzaType::Deluxe);
    let price = pizza.get_price();
    println!("{}", price);
}

Pizza example:

public abstract class Pizza
{
    public abstract decimal GetPrice();

    public enum PizzaType
    {
        HamMushroom, Deluxe, Hawaiian
    }
    public static Pizza PizzaFactory(PizzaType pizzaType)
    {
        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                return new HamAndMushroomPizza();

            case PizzaType.Deluxe:
                return new DeluxePizza();

            case PizzaType.Hawaiian:
                return new HawaiianPizza();

            default:
                break;
        }

        throw new System.NotSupportedException("The pizza type " + pizzaType.ToString() + " is not recognized.");
    }
}
public class HamAndMushroomPizza : Pizza
{
    private decimal price = 8.5M;
    public override decimal GetPrice() { return price; }
}

public class DeluxePizza : Pizza
{
    private decimal price = 10.5M;
    public override decimal GetPrice() { return price; }
}

public class HawaiianPizza : Pizza
{
    private decimal price = 11.5M;
    public override decimal GetPrice() { return price; }
}

// Somewhere in the code
...
  Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice().ToString("C2") ); // $11.50
...
<pro>

private class Pro : Pizza

Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice().ToString("C2") ); // $11.50

Pizza example:

#include <string>
#include <iostream>
#include <memory> // std::auto_ptr
class Pizza {
public:
    virtual void get_price() const = 0;
    virtual ~Pizza() {};
};
 
class HamAndMushroomPizza: public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Ham and Mushroom: $8.5" << std::endl;
    }
};
 
class DeluxePizza : public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Deluxe: $10.5" << std::endl;
    }
};

class HawaiianPizza : public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Hawaiian: $11.5" << std::endl;
    }
};
 
class PizzaFactory {
public:
    static Pizza* create_pizza(const std::string& type) {
        if (type == "Ham and Mushroom")
            return new HamAndMushroomPizza();
        else if (type == "Hawaiian")
            return new HawaiianPizza();
        else
            return new DeluxePizza();
    }
};
//usage
int main() {
 
    std::auto_ptr<const Pizza> pizza(PizzaFactory::create_pizza("Default"));
    pizza->get_price();
 
    pizza.reset(PizzaFactory::create_pizza("Ham and Mushroom"));
    pizza->get_price();

    pizza.reset(PizzaFactory::create_pizza("Hawaiian"));
    pizza->get_price();
}

JavaScript

edytuj

Pizza example:

//Our pizzas
function HamAndMushroomPizza(){
  var price = 8.50;
  this.getPrice = function(){
    return price;
  }
}

function DeluxePizza(){
  var price = 10.50;
  this.getPrice = function(){
    return price;
  }
}

function HawaiianPizza(){
  var price = 11.50;
  this.getPrice = function(){
    return price;
  }
}

//Pizza Factory
function PizzaFactory(){
  this.createPizza = function(type){
     switch(type){
      case "Ham and Mushroom":
        return new HamAndMushroomPizza();
      case "Hawaiian":
        return new HawaiianPizza();
      default:
          return new DeluxePizza();
     }     
  }
}
//Usage
var pizzaPrice = new PizzaFactory().createPizza("Ham and Mushroom").getPrice();
alert(pizzaPrice);

Pizza example:

class HamAndMushroomPizza
  def price
    8.50
  end
end

class DeluxePizza
  def price
    10.50
  end
end

class HawaiianPizza
  def price
    11.50
  end
end

class ChunkyBaconPizza
  def price
    19.95
  end
end

class PizzaFactory
  def create_pizza(style='')
    case style
      when 'Ham and Mushroom'
        HamAndMushroomPizza.new
      when 'Deluxe'
        DeluxePizza.new
      when 'Hawaiian'
        HawaiianPizza.new
      when 'WithChunkyBacon'
        ChunkyBaconPizza.new
      else
        DeluxePizza.new
    end   
  end
end

# usage
factory = PizzaFactory.new
pizza = factory.create_pizza('Ham and Mushroom')
pizza.price #=> 8.5
# bonus formatting
formatted_price = sprintf("$%.2f", pizza.price) #=> "$8.50"
# one liner
sprintf("$%.2f", PizzaFactory.new.create_pizza('Ham and Mushroom').price) #=> "$8.50"

Python

edytuj
# Our Pizzas

class Pizza(object):
    PIZZA_TYPE_HAM_MUSHROOM, PIZZA_TYPE_DELUXE, PIZZA_TYPE_HAWAIIAN = xrange(3)
    def __init__(self): self.price = None
    def getPrice(self): return self.price
class HamAndMushroomPizza(Pizza):
    def __init__(self): self.price = 8.50

class DeluxePizza(Pizza):
    def __init__(self): self.price = 10.50

class HawaiianPizza(Pizza):
    def __init__(self): self.price = 11.50

class PizzaFactory(object):
    def make(self, pizzaType):
        classByType = {
            Pizza.PIZZA_TYPE_HAM_MUSHROOM: HamAndMushroomPizza,
            Pizza.PIZZA_TYPE_DELUXE: DeluxePizza,
            Pizza.PIZZA_TYPE_HAWAIIAN: HawaiianPizza,
        }
        return classByType[pizzaType]()

# Usage
print '$ %.02f' % PizzaFactory().make(Pizza.PIZZA_TYPE_HAM_MUSHROOM).getPrice()


// Our Pizzas
abstract class Pizza {
    abstract public function get_price();
}

class HamAndMushroomPizza extends Pizza {
    public function get_price() {
        return 8.5;
    }
}

class DeluxePizza extends Pizza {
    public function get_price() {
        return 10.5;
    }
}

class HawaiianPizza extends Pizza {
    public function get_price() {
        return 11.5;
    }
}

class PizzaFactory {
    public static function create_pizza( $type ) {
        switch( $type ) {
            case 'Ham and Mushroom':
                return new HamAndMushroomPizza();
                break;
            case 'Hawaiian':
                return new HawaiianPizza();
                break;
            default:
                return new DeluxePizza();
        }
    }
}
// Usage
$pizza = PizzaFactory::create_pizza( 'Hawaiian' );
echo $pizza->get_price();


Haskell

edytuj

Pizza example:

class Pizza a where
  price :: a -> Float

data HamMushroom = HamMushroom
data Deluxe      = Deluxe     
data Hawaiian    = Hawaiian   

instance Pizza HamMushroom where
  price _ = 8.50

instance Pizza Deluxe where
  price _ = 10.50

instance Pizza Hawaiian where
  price _ = 11.50

Usage example:

main = print (price Hawaiian)