It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
in Abstract Factory design pattern , a class delegates the responsibility of object instantiation to another object via composition.
can some one explain it with some example.
I'll tell you a traditional example about that. Imagine you have a UI library. It have implementation of different UI components like buttons, sliders, radio buttons, etc. You also want to have different look-and-feel of these components, for example silver, dark, light, windows-like, gtk-like etc. You can use an abstract class which makes the common things for each component's creation and child classes which inherit from the abstract and specifies only the differences:
class AbstractComponentFactory {
public abstract Button createButton() {
//implementation
}
public abstract Slider createSlider() {
//implementation
}
}
class SilverComponentFactory extends AbstractFactory {
public Button createButton() {
Button b = base.createButton();
//customize the button
}
public Slider createSlider() {
Slider b = base.createSlider();
//customize the slider
}
}
class WindowsComponentFactory extends AbstractFactory {
public Button createButton() {
Button b = base.createButton();
//customize the button with windows look-and-feel
}
public Slider createSlider() {
Slider b = base.createSlider();
//customize the slider with windows look-and-feel
}
}
Now if you need to create components you can change dynamically the implementation of the Abstract factory:
public void createUI(AbstractComponentFactory f) {
Button b = f.createButton();
Slider s = f.createSlider();
}
//..
createUI(new SilverComponentFactory());
Here is a sample class diagram, I hope it's not so complex.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
i have a message object that i can add content to. The message can also be sent. Is it better to provide a "deep module" that hides the dispatcher from the client, or is it better to have only one responsibility per class?
Example: expose the dispatcher
class Message {
void add(String key, String value) { ... }
}
class Dispatcher {
Result send(Message message) { ... }
}
class DispatcherFactory {
Dispatcher create() { return new DefaultDispatcher(); }
}
Example: Hide the dispatcher
class MessageFactory {
Message create() { return new Message(DefaultDispatcher()); }
}
class Message {
Message(Dispatcher dispatcher) { ... }
void add(String key, String value) { ... }
Result send() {
return dispatcher.dispatch(content);
}
}
In my opinion the latter is easier to use and also testable, but violates the SRP. Which one is better?
In my opinion the latter is easier to use and also testable, but violates the SRP
it does not violate SRP as implementation of Dispatcher class is located in Dispatcher class. If Message class would have implentation of Dispatcher class, then it will be violtion of SRP class.
Which one is better?
In my view, the second implementation is better if you can slightly modify your implementation of MessageFactory Mediator pattern.
Let me show an example:
class MessageFactory {
Message create(DefaultDispatcher defaultDispatcher)
{ return new Message(defaultDispatcher); }
}
UPDATE:
If you want to have relationship publisher and subscriber. I mean publisher send messages to subscribers, then you can use Observer pattern.
As wiki says about Observer pattern:
The observer pattern is a software design pattern in which an object,
named the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.
The Open/Closed Principle states that software entities (classes, modules, etc.) should be open for extension, but closed for modification. I learned about this today and my teacher said that this concept is intrinsically connected to the concept of polymorphism. I can´t really see how both concepts are connected, can anyone explain please?
Here's my exaplanation.
Look at the following example:
public interface IShape
{
void Draw();
}
public class Square : IShape
{
public void Draw()
{
// DRAW SQUARE
}
}
public class Circle : IShape
{
public void Draw()
{
// DRAW CIRCLE
}
}
public class Renderer
{
public void DrawShapes(ICollection<IShape> shapes)
{
foreach (var shape in shapes)
{
shape.Draw();
}
}
}
This code is open to extensions and closed to modifications therefore it follows the OCP principle. Why? In case you need to make the application able to draw a new shape (e.g. Triangle), you don't need to modify the DrawShapes method of the Render class.
You only need to create a new class "Triangle" that implements the interface IShape and pass it to the DrawShapes method.
This code is also polymorphic because the "DrawShapes" method does not need to know the types of the shapes that it is rendering.
Pay attention to one thing: the closure of the O.C.P. principle is always strategic. What does it mean? It means that you cannot have code that is 100% closed to modifications. Example: what happens if you need to draw all the squares before the circles? In that case you have to modify the DrawShapes method; maybe with a Strategy pattern you can inject the policy to sort the drawing of the shapes.
I have a Layout Manager Class and this class designed for setting datagrid layout.
Code:
class LayoutManager
{
private object _target;
public LayoutManager(object aDataGrid)
{
_target = aDataGrid;
}
public void SaveLayout(string strProfileID)
{
}
public void LoadLayout(string strProfileID)
{
}
//in future I might add below function
public void ResetLayout()//OtherFunction0
{
}
public void OtherFunction1()
{
}
public void OtherFunction2()
{
}
}
According to OCP "a Class should be open for extension, but closed for modification". If I add the new function in LayoutManager Class, is this action violate the OCP? If yes, what is the proper way to design the class?
I don't think that adding methods to a class in general violates the OCP prinicple,
as this in fact extends the class's behviour.
The problem is if you change existing behaviours.
So that if the code on your added methods might change the behaviour of the existing methods
(because it changes the object's state) that would be a violation.
The correct way to follow the SOLID principals, is to make an interface:
ILayoutManager with the interfaces you want , with documented behaviours.
The class LayoutManager would implement this interface.
Other new methods might be added in a new interface, say ILayoutFoo or added to the existing interface, as long as they won't break the contract of the documented behaviour in the existing methods.
It's not possible to directly answer this without some concrete code.
Generally speaking though, the upshot of the OCP is that when classes derive from your base class and then override methods, the internal invariants shouldn't break because that's modification. There shouldn't be any way for the derived class to change those parts of the class' behaviour. The derived classes can change behaviour or add new functionality by using the parts exposed by the base class.
Whenever we speak about Open-Closed Principle, one important issue comes into play, which is called Strategic Closure.
It should be clear that no significant program can be 100% closed. In general, no matter how “closed” a module is, there will always be some kind of change against which it is not closed. Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his design. This takes a certain amount of prescience derived from experience. The experienced designer knows the users and the industry well enough to judge the probability of different kinds of changes. He then makes sure that the open-closed principle is invoked for the most probable changes.
For example in famous sample of Shape class you just grantee that your program (in side of Client and Shape)just is closed for modification about adding new shape.
public class Shape {
public draw() {
}
}
public class Circle extends Shape {
#Override
public void draw() {
// implementation special to Circle
}
}
public class Client {
...
public drawMyShape(Shape shape) {
shape.draw();
}
...
}
According to this Strategy, when you are designing your program, you should make a decision about the sections that you want to be closed to changes. Therefore, in your example, when you were designing your program, if you decided that your entity (in this case it is GraphCalculator class) should be closed for modification and open to extension regarding to adding new functionality, adding new function in this example violates Open-Closed Principle, due to the fact that it changes implementation in side of client and GraphCalculator class. And solution can be using abstraction, which is mentioned in previous answers.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I came across such a OOP design on web(a brief version):
public abstract class ChessPieceBase {
abstract boolean canBeChecked();
abstract boolean isSupportCastle();
}
public class King extends ChessPieceBase { ... }
public class Queen extends ChessPieceBase { ... }
public class Position { // represents chess positions in compact form
ArrayList<ChessPieceBase> black;
ArrayList<ChessPieceBase> white;
}
public class ChessPieceTurn { };
public abstract class PlayerBase {
public abstract ChessPieceTurn getTurn(Position p);
}
class ComputerPlayer extends PlayerBase {
public ChessPieceTurn getTurn(Position p) { return null; }
}
public class HumanPlayer extends PlayerBase {
public ChessPieceTurn getTurn(Position p) { return null; }
}
public class GameManager {
void processTurn(PlayerBase player) { };
boolean acceptTurn(ChessPieceTurn turn) { return true; };
Position currentPosition;
}
I have some difficulty understanding the design, not knowing if i did not understand OOP or understanding chess :(. From top to bottom:
ChessPieceBase is the abstract base class for all pieces, king, queen, rook, bishop, knight, and pawn, right? so i see King and Queen extend ChessPieceBase.
Position, according to comments, should record a global current positions of pieces for black and white. It is implemented as an arraylist of ChessPieceBase, but ChessPieceBase does not contain any position info member, so where is position info stored?
what's ChessPieceTurn? if it's a 'my turn, your turn' concept, why getTurn() func in player class need 'Position p' parameter and return null?
GameManager class. 'currentPosition' record a global state of the game, 'acceptTurn()' does not seem to do anything, 'processTurn()' get turn from player and handle like referee. Hope i understand this last one correct.
And if possible, can someone write a little main() function to show how it works? At this time i am just confused.
Any idea from you on how you see what classes should look like for chess game are welcome,
Thanks,
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
User Login functionality is very common to many applications. I would like to see how people implement this functionality in Object oriented way.
I have a User and I need to validate the userId and password against a system(this could be ldap, database, etc.). So what kind of classes and operations you would create to achieve this functionality?
Or is OO a bad choice to develop this functionality?
I am about to start a new project so want to gather good options.
I know there are frameworks which provide this solution already. I have used them in earlier projects. What I was trying to see is how people implement this in OO way.
I read the answers and everybody suggested a separate Credentials and Authentication Service. If instead of Credentials I use class name as User then shouldn't User class should have a method called login? Just like a Person object will have a method drink instead of DrinkService or I am wrong in understanding this correctly?
Exactly how extensible does it need to be? I'd define an abstract class, Credentials, that encapsulates the needed authentication information for a given system. Subclass it for specific system types. An example would be BasicCredentials that contains only username and password. Then, define an interface that defines methods for authentication. Maybe I'd also define an abstract Host class that includes additional host information. This may be too much abstraction, depending on what you envision authenticating against.
This example code is C# 3.0.
public abstract class Credentials
{
}
public class BasicCredentials : Credentials
{
public String Username { get; set; }
public String Password { get; set; }
}
public abstract class Host
{
}
public class IPHost : Host
{
public IPAddress Location { get; set; }
}
public interface IAuthenticate
{
bool Authenticate(Credentials creds, Host host);
}
public class BasicAuthenticator : IAuthenticate
{
public bool Authenticate(Credentials creds, Host host)
{
// Check to make sure we're given the right type of parameters
if (creds is BasicCredentials && host is IPHost)
{
// Do your magic here
}
}
}
Or is OO a bad choice to develop this functionality?
I don't think usage of OO limits you in any way, so the question should rather be, can I afford building this part with OO? Other styles could be a lot faster.
That having said, I'd create the following classes:
Credentials
AuthenticationService
Furthermore, the class User would require a getCredentials() function. This approach means, that you're always authenticating using username/password, though. For an even broader approach, let the AuthenticationService operate on the User object itself.
If you want an OO solution I'd go for using an OO language and writing some classes ;-).
But seriously, at the basic level you're going to want a databean to store the login information, let's call that "Login". I'd then go for a service that provides authentication, let's call that "AuthenticationService". Finally you can provide concrete implementations of each of the different kind of authentication schemes you need. So you're gonna have something like:
public class Login {
private String loginName;
private String password;
/* getters / setters */
}
public interface AuthenticationService {
public boolean isLoginValid(Login login);
}
public class LdapAuthenticationService implements AuthenticationService {
public boolean isLoginValid(Login login) {
/* LDAP specifics here */
}
}
public class DatabaseAuthenticationService implements AuthenticationService {
public boolean isLoginValid(Login login) {
/* database specifics here */
}
}
Use dependency-injection to get the required concrete implementation into your system depending on what your current needs are.
Authentication also involves retrieving credentials and you will want to include how the credentials are accessed in your authentication framework. This can be even more important than the Authenticator class already highlighted.
class CredentialsAccessor {
public bool hasCredentials(){};
public Credentials getCredentials();
}
class FormAccessor : CredentialsAccessor {
// get credentials from a webapp or form
}
class CookieAccessor : CredentialsAccessor {
// get credentials based on cookie
}
class SessionAccessor : CredentialsAccessor {
// get credentials from user session
}
class CredentialAccessManager
{
list<CredentialsAccessor> m_Credentials;
Credentials getCredentials()
{
foreach( CredentialsAccessor l_accessor in m_Credentials )
{
if( l_accessor.hasCredentials() ) return l_accessor.credentials();
}
}
}
You plug all the accessor objects into the list in the right order and your user will magically be logged in every time.
The object-oriented approach is to use the provided classes or find a library and subclass it if it doesn't already do what you want :)