Reconstruction version of the computer room fee system layer, interface, database connection, Reflection + factory (vb.net)

Source: Internet
Author: User
Tags sql client reflection access database


Layered

Layering is to reduce the dependency between layer and layer, increase the readability of the program, make the whole system structure clear and clear, but also can greatly reduce maintenance costs, but there are some shortcomings in the hierarchy, some can directly access the database layer, but through the database to access the layer to access, so, In the process of accessing the database, there is a link, increase the overhead of the system, sometimes to add a function in the presentation layer, in order to reduce the coupling, you have to top-down, in each layer to increase the functionality required by the service class, which increases the development cost

The more layered the better? The answer is no, quote a sentence "We must always remember: can not be blindly layered, should not be layered and layered should not pattern and pattern." This is very important. Otherwise it can only increase the burden of development (better experience in the future practice). "should be said to be based on the actual situation of layering, after all, is not absolute, because some systems do not layered score layer a bit more."

The basic layering is primarily a three-tier architecture:

presentation Layer (UI)

mainly used for interaction with the user, responsible for conveying the user's instructions and data to the BLL layer, and the user needs to display the data, popular speaking is the user can see the interface, such as the form of the program.

Business Logic Layer (BLL)

The logical processing of data, such as the data obtained from the Access database, to the user to see the data, and submitted to the presentation layer for display.

Data Access Layer (DAL)

access to the database, and other operations to provide additions and deletions.

Here is my package diagram, where each package is a layer with the addition of the solid layer (Model), Interface layer (Idal), and Factory layer (Factory)



Solid Layer (Model)

is actually the corresponding database inside each table, a table is built a class, a class inside the property is the corresponding table inside the field, such as table Basedata_info


In the entity layer, you can create a class like this:

Public Class basedataentity Inherits Entity Private fixeduserhalfhourcost as single ' fixed user spends half an hour public Prop  Erty Fixduserhalfhourcost_ as single get Return fixeduserhalfhourcost End Get Set (value as Single) Fixeduserhalfhourcost = value End Set End Property Private Casualuseranhourcost as Singl         E ' Temporary user spends one hour public property casualuseranhourcost_ as a single Get Return casualuseranhourcost End Get Set (value as single) Casualuseranhourcost = value End Set End Property Private I Ncreasingunittime as single unit increment time public property increasingunittime_ as single Get Return incre Asingunittime End Get Set (value as single) Increasingunittime = value End Set End Prope            Rty Private atleastonlinetime as single ' minimum online time public property atleastonlinetime_ as a single Get Return AtleastonliNetime End Get Set (value as single) Atleastonlinetime = value End Set End Property        Private Readytime as single ' Prep time public property readytime_ as single Get Return readytime  End Get Set (value as single) Readytime = value End Set End Property Private Atleastmoney        As single minimum Amount public property Atleastmoney_ as single get Return Atleastmoney End Get Set (value as single) Atleastmoney = value End Set End Property End Class


What's the use of it? When you need to register a user, you have to pass the data from the presentation layer (UI) to the data Access layer (DAL) used to access the database, but you cannot register the user information: study number, name, card number, registration date, registration time, class ... Wait, pass the arguments to the function, do you add the line?

    ' You don't really do that, do you? ' Was frightened by the    AddUser (Studentid,studentname,cardid,registerdate,registertime,class ... )    ' And if you encapsulate this data into a class like the one above, you just have to pass a class on the line    AddUser (UserInfo)

Database connection

For database access, basically what language can be separated from such a few steps:

1. Connect to the database

2. Execute SQL statements

3. Return the execution structure of the SQL statement

You can refer to the database connection string in the database connection string.

Execute SQL statement can refer to SQL statement Daquan

Here is a simple example of database access:

ImportsSystem.Data.SqlClient   ' Reference SQL Client public Class selectdal public    Overloads Function Selectinfo (ByVal Table As String)     ' query entire table        Dim DataS As New DataSet        Try            Dim selectstr As String = "select * from" & Tabl E     ' query statement            Dim connectstr as String = "Data source= server name/server address; Initial catalog= database name; Userid=sa; password=123 "' Database connection string            Dim DBConnection as New SqlConnection (CONNECTSTR) ' Initialize database connection object             Dbconnection.open () ' Connect to Database            ' Dim dbcmd As New SqlCommand (selectstr,dbconnection)    ' Execute query Statement            Dim Adapter As New SqlDataAdapter ( selectstr,dbconnection)  ' Save the query results to the cache             Adapter.fill (DataS, table)      ' Save the table in the cache to the DataSet          as table name Catch ex as Exception            Throw New argumentoutofrangeexception ("" & Ex. Message)       End Try         Return DataS End Function

the object to which the connection database is to be used is SqlConnection, executing the query statement and returning the result with the SqlDataAdapter object.

There are many ways to connect a database, such as local, remote, and so on. As long as the reference database connection string, according to their own circumstances to choose to use can achieve the purpose.

Reflection + Factory, interface

for reflection, at first I was very dazed, in the design mode, after knocking the example, looked up a lot of information, do not know how to apply to the toll system, really stupid home. However, later saw the Tall Man's blog, will be. See:


If you have a BLL and a DAL2 layer, you want a Class A in the BLL to use the Balancedal class in the DAL, you can do this by referencing the DAL, but it is said to reduce the coupling between the BLL and the DAL, So an interface layer was added between the BLL and the Dal called Idal. As


you can see that the box is the Balancedal interface in the above Dal, which contains all the methods of the concrete class (Balancedal), so as long as we invoke the interface, it is equivalent to invoking the specific class (Balancedal), but The premise is that you have to connect the interface and the specific class, like TV and remote control, the remote control is the TV interface, to the remote control interface, the TV should have a can receive and process infrared new number of devices, when you use the remote control, the remote control with the TV is Unicom, they through the infrared unicom. In fact, the relationship between the interface and the specific class, just create a pipeline between the two, the interface does not have a specific function, but there is a specific class using a method (like the keys on the remote control), if the remote control and the TV is not connected, then you click the remote control, you will not realize the power-on or FM functions, Therefore, to use the interface, the interface must be connected with the specific implementation of the class, here are two steps, the first step is a reference, the second step is to create an instance. See:



In the DAL's reference to the Idal tick on the line is equivalent to the two layers between the bridge, next, we let the DAL to implement this interface, that is, after creating a specific class in the DAL, write the keyword + The interface you want to implement, and then enter, it will automatically list the way you write in the interface, Then in the method, you go to the concrete implementation of it.


Then, we need to add a pipeline on the bridge, add the pipeline, that is, the interface method and the specific class of methods to connect, so that I in the BLL layer inside the Call interface method, is equivalent to call the specific class method, but I do not know the BLL of the specific class is how to achieve, it is said that This is to reduce the coupling between the BLL layer and the DAL layer, because I only care about the interface Idal. Look at the code below to see how the interface is used in the BLL

Imports system.reflection           ' reflected reference public CLASSBALANCEBLL    functionbalancequery (ByVal CardID asstring)        Ifcardid = "            then Thrownewargumentoutofrangeexception (" "," Enter card number: ")        EndIf dimibalance as         idal. Ibalance    ' balance interface       ibalance = CType (Assembly.Load ("DAL"). CreateInstance ("DAL. Balancedal "), Idal. ibalance)   ' Get balance class        Dimds as NewDataSet        Try            DS = ibalance.selectbalanceinfo (CardID) ' Query and return dataset results            ifds.tables (0). Rows.Count < 1 then               Throw newargumentoutofrangeexception ("", "no balance record for this card number")            EndIf        Catchex as Exception            thrownewargumentoutofrangeexception ("", ex. Message)        endtry        returnds    endfunction

Here, we first refer to the reflection, then create the interface (Ibalance), and then by reflection, the Balancedal concrete class instances in the DAL layer are reflected to the interface, so that we are equivalent to the interface and the concrete class connected to the pipeline, Then we can use the method of the concrete class: Ibalance.selectbalanceinfo (CardID)' Query and return the dataset result

Later found that the DAL layer inside the class reflected into the BLL layer, it is equivalent to the BLL layer inside the production of the DAL layer of the class, and then reflect the specific class of those code, I abstracted a layer, called factory layer, as long as the BLL reference factory, can be returned through the factory concrete class. This is the application of Reflection + factory.

Seems to write a little long, there are overloaded, configuration files, exception handling, stored procedures and other practical points of the technology to write, forget, put the next article. Hope to be of help to everyone.

Although object-oriented more complex, but the overall feeling, it is a lot of complex things to classify, block, layered, sub ... Then use the line to get them up, you don't have to completely remember all the pieces, but you can follow those drawings without preserving the details, as long as to get used to this way of thinking, it is not too difficult to believe.


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.