A Simple Factory Pattern returns an instance of one of the several classes depending upon the parameters passed to the shared/non-shared factory method.
Typically, all these classes are inherited from a common parent class. Each of them has common methods. But each of them has their own optimization task operation on data.
The following code implements the Simple Factory Pattern for the School Login System.
This application allows multi-access level user to login into the school system. Depending upon their userid/password they will be instantiated.
SchoolPrincipal and SchoolTeacher are the classes derived from the SchoolUser base class. There is a UserFactory class which is responsible to instantiate the appropriate class instance (SchoolPrincipal or SchoolTeacher) depending upon the userid/password passed to its shared method GetSchoolUser.
This method is entirely responsible for returning the appropriate class instance no matter how complex logic is involved.
Diagram:
Base Class:
Public Class SchoolUser
Public _Fname As String
Public _Lname As String
Public _UserType As String
Sub New()
End Sub
End Class
Derived Classes:
1. This class is for School Principal
Public Class SchoolPrincipal
Inherits SchoolUser
Sub New()
_Fname = "David "
_Lname = "Smith "
_UserType = "Principal"
End Sub
End Class
2. This class is for SchoolTeacher
Public Class SchoolTeacher
Inherits SchoolUser
Sub New()
_Fname = "Patrecia"
_Lname = "Terry"
_UserType = "Teacher"
End Sub
End Class
Factory Class:
Public Class UserFactory
Shared Function GetSchoolUser(ByVal _login As String,_
ByVal _paswrd As String) As SchoolUser
If _login = "principal" And _paswrd = "principal" Then
Return New SchoolPrincipal()
ElseIf _login = "teacher" And _paswrd = "teacher" Then
Return New SchoolTeacher()
Else
Throw New Exception()
End If
End Function
End Class
Client application using the factory:
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim m_OUser As SchoolUser = UserFactory.GetSchoolUser(TextBox1.Text, TextBox2.Text)
MsgBox("User Type: " & m_OUser._UserType & vbNewLine & "Name: " & m_OUser._Fname & " " & m_OUser._Lname)
End Sub
Enjoy
本文介绍简单工厂模式,它根据传入参数返回多个类的实例,这些类通常继承自同一父类且有各自的数据优化操作。以学校登录系统为例,展示了如何用简单工厂模式实现多用户登录,包含基类、派生类、工厂类及客户端应用代码。
1178

被折叠的 条评论
为什么被折叠?



