Application Example of factory model

Source: Internet
Author: User
Tags reserved advantage


Just take the computer room toll system.

Number One

Simple use of abstract factory to achieve. Such benefits are based on the overall system, not just from the original D, the ancient cloud: The parents ' son is far-reaching. This makes the system easier to expand. Because this inside except SqlHelper all use entity package, the line of entity package is omitted.

Number two

A "simple factory" to transform the abstract factory.

The simple factory here says just because it has no factory interface. In fact, because our computer room charge system is used to create a cluster of products used, supposedly a cluster of products should be abstract factory. The advantage is that, in the D-level to realize decoupling, and abstract factory compared to, we want to expand, BLL layer and ifactory change larger.

Number THREE

Combined with the "simple Factory" and the abstract factory, add the configuration file.

The difference with number one is to strip out a line. The advantage of such a child is the addition of dalfactory to the actual functional class dal coupling.

Of course, if you find a balance, our best choice is to use number THREE.

The code is as follows. (The code is logged in as an example.) UI omitted)

Number One

BLL layer.

'------------------------------------------------------------------------------'  <copyright file= "Daluser.vb"  company= "FANG" > '  Copyright  (c)  2012 FANG. All rights 
Reserved. '  <copyright> '  <author>The Sky Always Sunshine<author> '  < author> my blog Address http://blog.csdn.net/xhf55555</author> '  <date>2012 year February 3 <date> '  
<description> ' BLL level login.
'  <description> '------------------------------------------------------------------------------ Public class bll_login     public function login (ByVal User  As entity.en_user)  as boolean         dim myuser  as new entity.en_user          ' Determine which database to instantiate to factory,
To implement DB Exchange.         dim factory as iFactory. Ifactory = new dalfactory.sqlserverfactory         dim  iuser as idal.
Iuser          ' with specific database access is relieved of dependency.         iuser = factory. CheckUser ()         myuser = iuser.getuser (User)          if myuser.userpwd = user.userpwd then              return true          else             Return  False         end if     end function End
  class


Idal layer.

' <summary> '
user table function interface.
' </summary> '
<remarks></remarks> public
Interface iuser
Function GetUser ( ByVal User as Entity.en_user) as Entity.en_user end
Interface

The DAL layer. (Take Sqlserveruser as an example.) )

Public class sqlserveruser : implements idal. Iuser     public function getuser (Byval user as entity.en_user)  as entity.en_user implements idal. Iuser.getuser         Dim ConnStr As String =  "data source=192.168.24.169;initial catalog=pc_chargesys; user id=sa; pwd=123456 "        dim conn as sqlconnection =  new sqlconnection (connstr)          '  Dim  Connection as new sqlhelp.connectionhelp         dim  sql As String =  "Select * from tb_user where userid= '"  & User.UserID &  "'"         dim cmd  as sqlcommand = neW sqlcommand (Sql, conn)         Dim read As  SqlDataReader         dim myuser as new entity.en_ User         try              conn. Open ()             read = cmd. ExecuteReader             read. Read ()             myuser.userid = read. Item ("")             myUser.UserPwd =  Read.
Item ("Userpwd")             return myuser         catch ex as exception               myuser.userid = 0              myUser.UserPwd =  ""              return myuser         end try   
   end function End class


Ifactory layer.

' <summary> '
defines the Operation factory interface. 
' </summary> '
<remarks></remarks> public
Interface ifactory
Function CheckUser () as Idal. Iuser End
Interface


Sqlserverfactory Concrete Operation Engineering class.

 '------------------------------------------------------------------------------'  < Copyright file= "Daluser.vb"  company= "FANG" > '  Copyright  (c)  2012 FANG. 
All rights reserved. '  <copyright> '  <author>The Sky Always Sunshine<author> '  < author> my blog Address http://blog.csdn.net/xhf55555</author> '  <date>2012 year February 3 <date> '  
<description> ' concrete Operation class factory implements abstract functional class interface.
'  <description> '------------------------------------------------------------------------------ Public class sqlserverfactory : implements ifactory.ifactory      Public function checkuser ()  as idal. Iuser implements ifactory.ifactory.checkuser         return  new dal. Sqlserveruser     end function End class 


Accessfactory (similar to SQL Server, no longer redundant.) )

The user entity class.

' User entity class. Public class en_user     Dim intUserID As Integer   '
Define the user number variable.
    Dim strUserName As String   ' defines the user name variable.
    Dim strUserPwd As String  ' defines the user password variable name.
    Dim strUserActor As String  ' Define user role variables.
    Dim vntUserRegDate As Date  ' Define user registration date.
    Dim strUserFlag As String  ' A variable that defines whether a user is legally labeled.
    Dim strUserType As String  ' Define user type variables.
     '  <summary>      '   User number attribute method.
     '  </summary>      '  <value></value>      '  <returns></returns>      '  <remarks ></remarks>     public propErty userid ()  as integer         get              return intuserid          end get         set (ByVal value As  integer)             intUserID = 
Value         end set     end property
     '  <summary>      '   Defines the user Name property method.
     '  </summary>      '  <value></value>      '  <returns></returns>      '  <remarks ></remarks>     public property username ()  as string          get             return strusername          end get         set ( byval value as string)              Strusername = value         end set      end property      '  <summary>      '  
Define user Password property method  .
     '  </summary>      '  <value></value>      '  <returns></returns>      '  <remarks ></remarks>     public property userpwd ()  as string          get              return struserpwd         end get          set (byval value as string)              struserpwd = value        
 end set     end property      '  <summary>
     '   Define user Role attribute methods.
     '  </summary>      '  <value></value>      '  <returns></returns>      '  <remarks ></remarks>     public property useractor ()  as string          get              return struseractor         eNd get         set (byval value as string)              struseractor = value          end set     end property    
  '  <summary>      '   defines the registration date variable.
     '  </summary>      '  <value></value>      '  <returns></returns>      '  <remarks ></remarks>     public property userregdate as date          get              return vntuserregdate         end get          set (Byval valuE as date)             vntuserregdate  = value         end set     End  property      '  <summary>      '   defines whether the user is legitimate. (see if it is already logged off)      '  </summary>      '  <value></ Value>      '  <returns></returns>      '  <
Remarks></remarks>     public property userflag as string         get              return struserflag         end get          set (byval value as string)               struserflag = value         end  set     end property      '  <summary>       '   Define user type variable (fixed user or temporary user)      '  </summary>    
  '  <value></value>      '  <returns></returns>      "'  <remarks></remarks>     public property  usertyep ()  as string         get              return strusertype          end get         set (ByVal value As  string)             strUserType =  Value &NBSP;&NBSP;&NBSp;     end set     end property End Class
 

Let's look at number two 's abstract factory with a simple factory makeover.

We have removed the Ifactory factory interface and his specific factory operation class, instead of using a dalfactory instead of a solution. In this way, the judgment of the functional class is put into the dalfactory through the selectcase to judge instead of by the instantiation.

The UI, Iuser, Accessuser, Sqlserveruser are invariant. So on the basis of the above changes, the code is as follows.

BLL layer code.

' <summary> ' The
user logs in to the business logic.
' </summary> '
<remarks></remarks> public
Class bll_login public
    Function Login (ByVal User as Entity.en_user) as Boolean
        Dim myuser as New entity.en_user
        ' to determine which database to use through a specific operation factory implementation.
        Dim dalfactory as New dalfactory.dfactory
        Dim Iuser as Idal. Iuser
        ' with specific database access was relieved of dependency.
        Iuser = Dalfactory.createuserinfo ()
        myuser = Iuser.getuser (User)
        If myuser.userpwd = user.userpwd Then return
            True
        Else return False ' If end '
        Function end
Class


Dalfactory layer.

Imports idal
' <summary> '
operation factory class.
' </summary> '
<remarks></remarks> public
Class dfactory
    ' Dim DataBase as string = "Access"
    Dim DataBase as String = "SQL"
    Function createuserinfo () as Idal. Iuser
        Dim db as Iuser
        Select case DataBase case
            "SQL"
                db = New DAL. Sqlserveruser
                ' case ' Access '   db = New DAL. Accessuser End

        Select return
        db end
    Function

Number THREE We changed the operation of the factory case with a reflex method, and said goodbye to the case. We use the case to judge too much death, the string is written dead in the dalfactory, our use of functional classes, not the functional class itself to determine themselves. We have to decide our own life events, so we can use reflection. This relieves the coupling of branch judgments.

Dalfactory code.

Imports Idal
Imports System.Reflection '
<summary> '
Operation factory class.
' </summary> '
<remarks></remarks> public
Class dfactory
    ' Dim DataBase as String = "Access"
    Dim DataBase As String = "Sql"
    Dim strDB As String = System.Configuration.ConfigurationSett Ings. AppSettings ("dbstring")
    Function createuserinfo () as Idal. Iuser return
        
        CType (Assembly.Load ("DAL"). CreateInstance ("DAL.") Sqlserveruser "& strDB), Idal. Iuser)end

    Function end

Class


The specific function class Sqlserveruser, just changed a sentence.

Public Class sqlserveruser:implements Idal. Iuser public Function GetUser (ByVal User as Entity.en_user) as Entity.en_user Implements. Iuser.getuser ' Dim connstr as String = ' Data source=192.168.24.169;initial catalog=pc_chargesys; User Id=sa;  pwd=123456 "Dim connstr As String = System.Configuration.ConfigurationSettings.AppSettings (" connstr ") Dim Conn as SqlConnection = New SqlConnection (connstr) ' Dim connection as new Sqlhelp.connectionhelp ' Connec tion. Connect () Dim sql As String = "SELECT * from Tb_user where userid= '" & User.userid & "'" Dim cmd A
        s SqlCommand = new SqlCommand (SQL, conn) Dim read As SqlDataReader Dim myuser As New Entity.en_user Try Conn. Open () Read = cmd. ExecuteReader read. Read () Myuser.userid = read. Item ("") Myuser.userpwd = read.
          Item ("Userpwd") return MyUser Catch ex as Exception  Myuser.userid = 0 Myuser.userpwd = "" Return MyUser end Try-end Function End Class


Basic principles of Factory model see: http://blog.csdn.net/xhf55555/article/details/7609272

In summary, we compare the simple factory, the factory method, and the abstract factory three models in the practical application. Our best combination is a simple factory transformation of the abstract factory plus configuration files, coupling degree and system opening and closing (for extended open, to modify closed), System maintainability and flexibility in our three package diagram. The author (Me) thinks, our design pattern is like the mathematical formula, the nimble use is good. When we're developing a system, we're thinking about things, not from the top down, we want to go from the bottom up, not because of decoupling and decoupling, but we from the system in the long run, so that we in the system in the continuous reconstruction of the problem, to continue to think, further abstraction, make the system more perfect. There is no perfect system, only a perfect process.

a lot of questions, you are welcome to come to teach.



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.