开发者

using interfaces - design pattern aspect

I am looking for a good and short article+examples of how working with开发者_JAVA技巧 interfaces. I am not interesting the technical part, but I need the design part. For example, how to programming using interfaces, when and how create implementations, design patterns for regular development with interfaces.

I have many similar classes that repeat themselves in several ways. I want to use interfaces and abstract classes in order to make things more modular - but I can't find out how to do it properly.


An interface defines a contract. It's a promise that an object will behave a certain way. Before learning about interfaces, you tend to think about objects in concrete terms. For example, suppose we have a list of products:

List<string> products = new List<string>() { "desktop", "laptop", "server" };

And we have a method that prints out our products:

void PrintProducts(List<string> products)
{
     foreach (string product in products)
     { 
          Console.WriteLine(product);
     }
}

Our method is coupled to the concrete type of a List. Does it need to be though? There's plenty of different types of collections in C#: Lists, Arrays, ReadOnlyCollection, etc. All you really need to do is loop through them. A list has a lot of methods that an array doesn't, but you're not using any of them here. Fortunately, they all implement the interface IEnumerable. That means they all are "contractually bound" to be able to be enumerated.

Changing the method like so:

void PrintProducts(IEnumerable<string> products)
{
     foreach (string product in products)
     { 
          Console.WriteLine(product);
     }
}

means that you can now pass in an array, or a list, or some unique container you yourself create.

Another example: Suppose you have a repository of data:

public class DatabaseRepository
{
    public void AddProduct(Product product)
    {
        // connect to the database
        // add the product
    }
}

And you have some class that needs this database:

public class ProductManager
{
    DatabaseRepository _repository;

    public ProductManager(DatabaseRepository repository)
    {
         _repository= repository;
    }
}

Unfortunately, this class is tied to your database. What if you decide to change to storing as an XML file, or storing in some cloud key-value store. You would have to change your ProductManager, which is difficult and error prone. Suppose instead though we defined an interface:

public interface IRepository {
    void AddProduct(Product product);
}

Changing our ProductManager class to use this interface instead:

public class ProductManager
{
    IRepository _repository;

    public ProductManager(IRepository repository)
    {
         _repository= repository;
    }
}

means that no matter what type repository it is, we know that there will always be a method AddProduct(Product product). We can now create our XML repository:

public class XMLRepository : IRepository 
{
    public void AddProduct(Product product)
    {
         // write to an XML file
    }
}

Now, we are free to pass in either repository:

ProductManager manager = new ProductManager(new DatabaseRepository())

or

ProductManager manager = new ProductManager(new XMLRepository())

and our ProductManager behaves exactly the same. It is completely unaware of what the concrete type is.

This becomes very useful when you get into unit testing. Inversion of Control is something you will want to read up on when you get a firm understanding of how interfaces work.


This book as been the canonical reference for design patterns and contains examples of using interfaces. However you may want to start at an even more fundamental level. Thinking in Java is what got me into object oriented programming, there are likely similar titles for C# though the content of the book should be mostly agnostic of the language. You may also search for online tutorials on object oriented programming.

Edit: Great book about patterns and their implementation and usage in C# is C# 3.0 Design Patterns


When To Use Interfaces An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package. The disadvantage is every method in the interface must be public. You might not want to expose everything.

When To Use Abstract classes An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.

or read this: http://mindprod.com/jgloss/interfacevsabstract.html


@Naor, its seems, based on your above comment "It doesn't seem logical to create interface for each class I have - right?" that the best book for you to read is HEAD FIRST; DESIGN PATTERNS - it has an incredible and easy way of teaching how to use an apply design patterns. I first read of them in this book and it has definetly changed my mind!!! By reading this you'll be able to read more complicated stuff like Martin Fowler, Patterns of Enterprise Application Archtecture - which I believe approaches exatcly what you want, real world applicatoins of patterns. Going straight to to GoF, or M. Fowler, or more complicated stuff may disspoint you or make you just lose time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜