Go language Implementation design mode (ii): Simple Factory

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

The simple factory is mainly used to solve the problem of object "creation". The following example is taken from the first chapter of "Big Talk design mode" to implement an extensible "calculator". When adding new functionality, there is no need to change the algorithm that was already implemented. Because it is a simple factory, we still need to modify the factory class accordingly.

1. First, we define a computational interface

package calctypeinterface {    SetData(data ...interface{})    float64}

2. Next, we implement two subclasses of this class, namely addition and subtraction
addition, which is added by two numbers:)

 PackageCalcImport "FMT"typeAddstruct{NUM1float64Num2float64}funcNewadd () *add {instance: =New(ADD)returnInstancefunc(A *add) SetData (Data ...Interface{}) {if Len(data)! =2{FMT. Println ("error,need-parameters")return}if_, OK: = Data[0]. (float64);!ok {fmt. Println ("error,need float64 parameters")return}if_, OK: = Data[1]. (float64);!ok {fmt. Println ("error,need float64 parameters")return} A.NUM1 = Data[0]. (float64) a.num2 = Data[1]. (float64)}func(A Add) Calcoperate ()float64{returnA.num1 + a.num2}

Subtraction, is to subtract two numbers:), I feel so cold ...

 PackageCalcImport "FMT"typeSubtractionstruct{NUM1float64Num2float64}funcNewsubtraction () *subtraction {instance: =New(subtraction)returnInstancefunc(A *subtraction) SetData (Data ...Interface{}) {if Len(data)! =2{FMT. Println ("error,need-parameters")return}if_, OK: = Data[0]. (float64);!ok {fmt. Println ("error,need float64 parameters")return}if_, OK: = Data[1]. (float64);!ok {fmt. Println ("error,need float64 parameters")return} A.NUM1 = Data[0]. (float64) a.num2 = Data[1]. (float64)}func(A subtraction) Calcoperate ()float64{returnA.NUM1-A.NUM2}

3. It's time to get it done, define a simple factory to instantiate these two classes

 PackageCalctypeCalcfactorystruct{}funcNewcalcfactory () *calcfactory {instance: =New(calcfactory)returnInstancefunc(f calcfactory) Createoperate (OpTypestring) Calcsuper {varOp calcsuperSwitchOpType { Case "+": op = Newadd () Case "-": op = newsubtraction ()default:Panic("Error! Dont have this operate ")    }returnOp

In this simple factory, we only pass in the corresponding operation method, such as "+", "-", to create the relevant arithmetic strategy. It will return an instance of an operation interface, and when we get this instance, we can invoke the method inside to perform the operation.

4. Testing

Simple Factory mode Project main. GoPackage Mainimport (."Calc"    "FMT") Func Main () {factory: = Newcalcfactory () op: = Factory. Createoperate("+") op. SetData(1.0,2.0) FMT. Println(OP. Calcoperate()) op = Factory. Createoperate("-") op. SetData(1.0,2.0) FMT. Println(OP. Calcoperate())/* Output: 3-1 */}

Now, our simple factory model is done, and when we need to add multiplication, we do not avoid modifying or compiling the completed addition and subtraction operations. We just need to add the corresponding structure of the multiplication, and with a new switch branch in the factory, we can complete the multiplication.

Because the go language does not allow the existence of sub-abstract classes, which allows me to implement a very strange function setdata (data ... interface{}). It can pass in multiple arbitrary objects to be used as the data we need in our structure. This is just an example of what the simple factory has to do, and you can refer to the 6th chapter in refactoring and Patterns: knowledge of creation . It's a very comprehensive story.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Related Article

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.