您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页Simple Factory Pattern

Simple Factory Pattern

来源:意榕旅游网

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务