工厂方法
工厂方法跟简单工厂一样、都是创建型的设计模式、他解决了简单工厂的违背开放封闭的缺点。
故事
主人……人家做饭好累的、女仆抱着我大腿说着、自从上次把她买进家、没做了几次饭就喊累……看着她那出处可怜的眼神、罢了、再招几个女仆吧、话说还没给第一个女仆起名字、就叫‘遥’吧、后来又招了‘媛’和‘悦’、然后让她们分别只做一道菜、遥做牛排、媛做红酒、悦做意大利面、这次每次我想吃牛排就直接跟遥说‘吃饭’,喝红酒就跟媛说‘吃饭’而不用说吃什么了、因为她们每个人只做一道菜、以后要再想吃别的、就再招个女仆、只做一道菜、也不影响现有的女仆、这样她们也不会抱怨喽、美女环绕、喝酒吃肉、神仙快活——
------UML图
如图所示、原先的女仆工厂换成了女仆接口、然后有特定的女仆去做个个食物、这样的好处就是、如果在加一个食物、只要再加一个女仆工厂、再加个食物类就行了、不违背开放封闭原则、不像简单工厂还要修改工厂类。
代码
<span style="font-size:18px;">Public Class Form1 '女仆接口 Public Interface IMaid Function IMakeFood() As Food '做食物的方法 End Interface '女仆遥 Public Class YAO : Implements IMaid Public Function IMakeFood() As Food Implements IMaid.IMakeFood Return New Beef '返回牛排实例化的类 End Function End Class '女仆媛 Public Class yuan : Implements IMaid Public Function IMakeFood() As Food Implements IMaid.IMakeFood Return New RedWine '返回红酒实例化的类 End Function End Class '女仆悦 Public Class yue : Implements IMaid Public Function IMakeFood() As Food Implements IMaid.IMakeFood Return New Noodles '返回意大利面实例化的类 End Function End Class Public MustInherit Class Food '抽象食物类 Overridable Function Edible() As String '被食用的方法 End Function End Class Public Class Beef : Inherits Food '牛排类 Overrides Function Edible() As String Dim str As String str = "牛排:我被吃掉~\(≧▽≦)/~啦啦啦" Return str End Function End Class Public Class RedWine : Inherits Food '红酒类 Overrides Function Edible() As String Dim str As String str = "红酒:我被喝掉~\(≧▽≦)/~啦啦啦" Return str End Function End Class Public Class Noodles : Inherits Food '红酒类 Overrides Function Edible() As String Dim str As String str = "意大利面:我被我吃掉~\(≧▽≦)/~啦啦啦" Return str End Function End Class '单机按钮 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim YAO As IMaid = New YAO '声明女仆实例化遥 Label1.Text = YAO.IMakeFood().Edible() '遥做牛排 End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim yuan As IMaid = New yuan '声明女仆实例化媛 Label1.Text = yuan.IMakeFood().Edible() '媛做牛排 End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click Dim yue As IMaid = New yue '声明女仆实例化悦 Label1.Text = yue.IMakeFood().Edible() '悦做牛排 End Sub End Class </span>
实际效果
扩展
再加一个女仆樱类、加一个披萨食物类
<span style="font-size:18px;"> Public Class pizz : Inherits Food '披萨 Overrides Function Edible() As String Dim str As String str = "披萨:我被吃掉~\(≧▽≦)/~啦啦啦" Return str End Function End Class '女仆樱 Public Class ying : Implements IMaid Public Function IMakeFood() As Food Implements IMaid.IMakeFood Return New pizz '返回披萨实例化的类 End Function End Class ‘单机按钮加一个 Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click Dim ying As IMaid = New ying '声明女仆实例化樱 Label1.Text = ying.IMakeFood().Edible() '樱做披萨 End Sub </span>
效果图
好处、两张图带
用设计模式之前的多对多关系、如果在加一个食物、你我他三个类都要做更改
用设计模式之后的、只要知道工厂类就行了、与食物类解耦和、扩展的话就加一个食物类加一个工厂类、客户端调用就行
—————————————————够明显了吧—————————————————
——————————工厂方法——————————
————chenchen————
设计模式-工厂方法(Demo)
时间: 2024-12-29 11:18:47