Method return an interface

前端 未结 6 1076
青春惊慌失措
青春惊慌失措 2021-02-02 01:18

Hi All,

I\'m thinking in this line of code

IDataReader myReader = questDatabase.ExecuteReader(getQuest);

I\'m using DA

6条回答
  •  轮回少年
    2021-02-02 01:34

    It allows you to you DataReader without the need of knowing which type of DataReader you are using (i.e. SqlDataReader, OleDbDataReader, EtcDataReader), so if someday you want to change the datareader you are using it won't impact you logic, in other words it gives you abstraction. For example :

    you can use

    IDbCommand command = GiveMeSomeCommand();
    IDataReader r = command.ExecuteReader();
    

    without knowing which provider you are using

    it can be:

    private static IDbCommand GiveMeSomeCommand()
    {
        return new OleDbCommand();
    }
    

    or it can be

    private static IDbCommand GiveMeSomeCommand()
    {
        return new SqlCommand();
    }
    

    or whatever.

    EDIT:

    You can also use the DBFactories.

    DbProviderFactory factory = GiveMeSomeFactory();
    IDbCommand command = factory.CreateCommand();
    IDataReader r = command.ExecuteReader();
    
    //and create more objects
    IDataAdapter adapter = factory.CreateDataAdapter();
    IDbConnection conn = factory.CreateConnection();
    

    and then create your provider in other layer

    private DbProviderFactory GiveMeSomeFactory()
    {
        if(something)
            return SqlClientFactory.Instance;
        else if(somethingElse)
            return OracleFactory.Instance;
        else if(notThisAndNotThat)
            return MySqlFactory.Instance;
        else
            return WhateverFactory.Instance;
    
    }
    

提交回复
热议问题