Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I wouldn't go so far to say that <code>new</code> is considered harmful. What the abstract factory pattern attempts to do is solve the problem that <code>new</code> is not overrideable (i.e. is not compatible with virtual dispatch, at least in languages like Java and C#).</p> <p>Consider this sample code (C#):</p> <pre><code>class Sender { private ISendChannel channel; public Sender() { } public void Connect(Uri endpointAddress) { // !! Sender is tightly coupled to TCP implementation // !! even though it doesn't apparently have to be. this.channel = new TcpSendChannel(endpointAddress); } /* ... */ } </code></pre> <p>In this code, we have a base interface <code>ISendChannel</code> to allow forward communication to some endpoint. However, the implementation as given is fixed to always use a TCP channel no matter what. This is not desirable because now if you want an HTTP sender, you either have to modify the <code>Sender</code> class or add new methods to it. This is "bad coupling".</p> <p>Instead, you could use a factory to create channels and pass it in to the sender. The sender will ask the <strong>factory</strong> to create the channel and thus give up that responsibility. The new implementation may look like this:</p> <pre><code>class Sender { private readonly ISendChannelFactory factory; private ISendChannel channel; public Sender(ISendChannelFactory factory) { this.factory = factory; } public void Connect(Uri endpointAddress) { // Sender does not have to care what type of channel it is. this.channel = this.factory.CreateSendChannel(endpointAddress); } /* ... */ } </code></pre> <p>Now to use an HTTP channel, you could instantiate a sender using a different factory type, e.g. <code>new Sender(new HttpSendChannelFactory(/* ... */));</code>. The <code>HttpSendChannelFactory</code> could then return <code>HttpSendChannel</code> (a concrete type deriving from <code>ISendChannel</code>) from its <code>CreateSendChannel</code> method.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload