Original design mode (Golang) Five, factory method mode

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Pattern feature: Defines an interface for creating objects, letting subclasses decide which class to instantiate. This causes the instantiation of a class to be deferred to its subclasses.
Program Example: Calculator.

Package Mainimport ("FMT") type operation struct {a float64b float64}type Operationi interface {getresult () Float64seta (fl Oat64) Setb (float64)}func (op *operation) SetA (a float64) {Op.a = A}func (op *operation) Setb (b float64) {op.b = B}type Add  Operation struct {operation}func (this *addoperation) GetResult () float64 {return this.a + this.b}type suboperation struct  {Operation}func (this *suboperation) GetResult () float64 {return this.a-this.b}type muloperation struct {operation}func (This *muloperation) GetResult () float64 {return THIS.A * this.b}type divoperation struct {operation}func (this *divoperation) GetResult () Floa T64 {return This.a/this.b}type ifactory interface {createoperation () Operation}type addfactory struct {}func (this *ADDF actory) createoperation () Operationi {return & (addoperation{})}type subfactory struct {}func (this *subfactory) CreateOperation () Operationi {return & (suboperation{})}type mulfactory struct {}func (this *mulfactory) CreateOperation () OperaTioni {return & (muloperation{})}type divfactory struct {}func (this *divfactory) createoperation () Operationi { Return & (divoperation{})}func Main () {FAC: = & (addfactory{}) Oper: = FAC. CreateOperation () Oper. SetA (1) Oper. SETB (2) fmt. Println (Oper. GetResult ())}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.