Design pattern using interface or abstract [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 years ago.
Improve this question
I am trying to calculate the print cost base on different paper size, single side or double side. So here is the detail:
Also need to support for other paper sizes will be added in the future.
And according to my design, developer can just create a A5 class for example to support other paper size, and add other condition in the factory class.
Could someone review my code and help me on whether I have to use interface instead of abstract class?
Here is my code:
PageBase:
public abstract class PageBase {
abstract double GetCost(int total, int color, boolean isSingleSide);
abstract void CalculateUnitPrice(boolean isSingleSide);
}
A4Page Class:
public class A4Page extends PageBase {
public double blackAndWhitePrintUnitCost;
public double colorPrintUniCost;
#Override
public double GetCost(int total, int color, boolean isSingleSide) {
CalculateUnitPrice(isSingleSide);
return color* colorPrintUniCost + (total-color)* blackAndWhitePrintUnitCost;
}
#Override
public void CalculateUnitPrice(boolean isSingleSide) {
if (isSingleSide) {
this.blackAndWhitePrintUnitCost = 0.15;
this.colorPrintUniCost = 0.25;
}
else {
this.blackAndWhitePrintUnitCost = 0.10;
this.colorPrintUniCost = 0.20;
}
}
}
PageFactory:
public class PageFactory {
public PageBase GetPage(String pageType) {
switch (pageType.toUpperCase()) {
case "A4":
return new A4Page();
default:
return new A4Page();
}
}
}
Main:
public class Main {
public static void Main() {
//read
PageFactory pageFactory = new PageFactory();
PageBase page = pageFactory.GetPage("A4");
page.GetCost(0,0,false);
}
}

Decorator is way more elegant than Factory to your problem.
For Decorator, you will need some classes and interfaces:
Interfaces: Colored, Side and Page. All interfaces has a method cost() to be implemented.
Classes: SingleSide, DoubleSide, ColorPage, BlankAndWhitePage, A4
Usage:
Page page1 = new A4(new SingleSide(new ColorPage()))
Page page2 = new A4(new DoubleSide(new BlankAndWhitePage()))
page1.cost();
You need to add some value to each component, to be summed and give the expected value. Each object has a "cost".
Some internals:
class A4 implements Page {
//constructor
private Side side;
public BigDecimal cost() {
return this.valueA4 + side.cost();
}
}
class SingleSide implements Side {
//constructor
private Colored colored;
public BigDecimal cost() {
return this.valueSingleSided+ colored.cost();
}
}
Something in this line could give you some insights about the best object organization.

Related

Classes with template method design

I have made this four classes and I'm wondering if I used the template method design pattern correctly because I'm really struggeling with this subject.
I have used the methods getPrijsBehandeling() and getBeschrijvingBehandeling() as my abstract classes.
Also I'm wondering if I should use the abstract methods in my UML or only in the code.
Since this is the first time I'm using a design pattern I wonder if I’m on the right track.
public abstract class Behandeling {
private String beschrijving;
private double prijs;
private int behandelingsNummer;
private Wassen wassen;
public Behandeling(int behandelingsNummber, int keuze) {
this.behandelingsNummer = behandelingsNummber;
if(keuze == 3 || keuze == 4) {
wassen = new Wassen();
}
}
public abstract double getPrijsBehandeling();
public abstract String getBeschrijvingBehandeling();
public double getPrijs() {
prijs = getPrijsBehandeling();
if(wassen != null) {
prijs += wassen.getPrijsBehandeling();
}
return prijs;
}
public String getBeschrijving() {
beschrijving = getBeschrijvingBehandeling();
if(wassen != null) {
beschrijving += wassen.getBeschrijvingBehandeling();
}
return beschrijving;
}
public int getBehandelingsNummer() {
return behandelingsNummer;
}
}
------------------------------------------
public class Verven extends Behandeling {
public Verven(int behandelingsNummer, int keuze) {
super(behandelingsNummer, keuze);
}
#Override
public double getPrijsBehandeling() {
return 20;
}
#Override
public String getBeschrijvingBehandeling() {
return "Haren worden geverfd";
}
}
---------------------------------------------
public class Knippen extends Behandeling{
public Knippen(int behandelingsNummer, int keuze) {
super(behandelingsNummer, keuze);
}
#Override
public double getPrijsBehandeling() {
return 15;
}
#Override
public String getBeschrijvingBehandeling() {
return "Haren worden geknipt";
}
}
-----------------------------------------------------
public class Wassen {
private double prijs;
private String beschrijving;
public Wassen() {
this.prijs = 7.50;
this.beschrijving = " en haren worden gewassen";
}
public double getPrijsBehandeling() {
return prijs;
}
public String getBeschrijvingBehandeling() {
return beschrijving;
}
}
The methods (aka “operation”, in UML speak) geefPrijs()and geefBeschrijving() are indeed designed according to the template method pattern: the base class implements the general algorithm, encapsulating the “primitive” parts that may need to be specialized into separate methods that can be overridden (i.e. “specialized”, in UML speak) by class extensions.
If the base class cannot provide its own implementation of a “partial” methods, you would make it abstract. But although this is how the pattern is usually described, in practice this is not an obligation: it is perfectly valid that the base class provides a default behavior that is not always overridden. The UML diagram should reflect your design in this regard, if there are abstract elements.
Some additional hints
In your design getPrijs() (template method) and getPrijsBehandeling() (primitive used in the template method) are both public and have names that create a risk of confusion:
if the primitive is not intended to be used for other purposes, it is one of the rare situation where making it protected could be a good idea.
if you prefer to avoid protected, you could use a naming convention. GoF suggests the “do” prefix inspired from a framework that didn’t survive. I prefer “prepare” like preparePrijsBehandeling() and prepareBeschrijvingBheandeling() because it immediately raises the question “prepare for what?” preventing inappropriate use.
It’s not the case here, but of course, if the primitive is a primitive operation that makes sense outside of the template methods, then there is no issue (example: surface() or perimeter() or barycenter() that are geometric characteristics of a shape that may be relevant for some template methods but make sense on their own).

Should I use an anonymous inner class to simulate 'out' parameters in Java?

I'm still a relative newbie when it comes to Java, coming mainly from a C# background.
I was discussing the lack of 'out' parameters in Java methods with a colleague and how to work around this. He suggested creating a structure/class to hold the various parameters and passing it back.
Sometimes this feels 'wrong' to me - especially if I have a special method that I want to use to return a subset of parameters from a larger class.
So I wondered about using anonymous inline classes instead to achieve this. Code sample below.
Is this a sensible approach? Just wondering what the perceived wisdom is on this.
public class MyClass {
Patient myPatient = null;
// An interface to enable us to return these variables in a single call
public interface VitalStatsResponse { public void returnStats(int bloodPressure, int heartRate); }
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Lots of other variables here
public void calculateVitalStats(VitalStatsResponse response)
{
response.returnStats((bloodPressure * 2), (heartRate / 10) ;
}
}
public void doWork()
{
// We want the patient's blood pressure and heart rate returned by a single method call, so use an anonymous inline class
myPatient.calculateVitalStats(new VitalStatsResponse() {
#Override
public void returnStats(int bloodPressure, int heartRate) {
// Handle returned variables here
}
});
}
}
I would go for the simple solution of creating a VitalStats object. If you need the VitalStatus of a patient, then VitalStats is a concept in your application that can be represented as an Object.
public class VitalStatus {
final int bloodPressure;
final int heartRate;
public VitalStats(int bloodPressure, int heartRate) {
this.bloodPressure = bloodPressure;
this.heartRate = heartRate;
}
}
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Other variables
public VitalStatus getVitalStatus() {
return new VitalStats(bloodPressured * 2, heartRate / 2);
}
}
Out params is a procedural solution for return times. Java primarily fits the Object Oriented paradigm of programming and as such don't be afraid to make objects. This fits with the S in SOLID if your class is doing a lot of complex things see if you can break it down into smaller more manageable pieces.
I would also use "class to hold the parameters" over "inline anonymous inner class"
public class MyClass implements VitalStatsResponse{
Patient myPatient = null;
private ArrayList<VitalStatsResponse> response;
void MyClass(ArrayList<VitalStatsResponse> response) {
this.response = response;
}
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Lots of other variables here
public void calculateVitalStats()
{
for(int i = 0; i < response.length; i++) {
// call returnStats method of every registered callback
response.get(i).returnStats((bloodPressure * 2), (heartRate / 10) ;
}
}
}
// any client can register/unregister callback via these methods
void registerResponse(VitalStatsResponse response) {
this.response.add(response);
}
void unRegisterResponse(VitalStatsResponse response) {
this.response.remove(response);
}
public void doWork()
{
// We want the patient's blood pressure and heart rate returned by a single method call, so use an anonymous inline class
myPatient.calculateVitalStats();
}
public void returnStats(int bloodPressure, int heartRate) {
// implement the body according to this class requirement
}
}

Java Basic Game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm tryin to develop a small text-based fighting game and I'm using eclipse to help me out. I have two classes a Hero and Villian.
Hero Code so far:
public class Hero
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Hero
*/
public Hero()
{
// initialise instance variables
Health = 100;
Punch = -30;
Kick = -25;
Special = -55;
}
Villian Code so far:
public class Villian
{
// instance variables - replace the example below with your own
private int Health;
private int Punch;
private int Kick;
private int Special;
/**
* Constructor for objects of class Villian
*/
public Villian()
{
// initialise instance variables
Health = 100;
Punch = -25;
Kick = -30;
Special = -50;
}
I want to make it turn-based as well so that when the hero attacks, it's the villian's turn. But I'm having trouble trying to construct a suitable method for the attacks. Can someone please help me with this?
The best way to solve this problem is to use inheritance.
You want to have one class called Entity which holds everything all things need on the game field:
public abstract class Entity {
private int Health;
private int attackDmg;
public Entity(int health, int attackDamage) {
this.health = health;
this.attackDamage = attackDamage;
}
}
Then the two classes you currently have simply inherent everything from Entity:
public class Hero extends Entity {
public Hero() {
super(100, 30);
}
}
and Villian:
public class Villian extends Entity {
public Villian() {
super(100, 20);
}
}
Now you probably want to have some methods that makes the Entity take damage. Because everybody should be able to take damage it comes into the Entity class. Also you probably want to have an attack method, that tells you how much damage the entities does:
public abstract class Entity {
// [...]
public void takeDamage(int damage) {
health -= dmg;
}
public void attack() {
return attackDamage;
}
}
Now you can write in your controller class (that handles all of the turn based logic):
player.takeDamage(villian.attack()); (Given that playeris your Playerand villian your Villian).
Of course this only is a small example, you could also make a method that take a String as an argument, which represents the method of the attack (like "kick" or "punch") and then return different amounts depending on the attack type.
Further infos to inheritance:
http://www.tutorialspoint.com/java/java_inheritance.htm and http://beginnersbook.com/2013/05/java-inheritance-types/
You might also be interested in a game making tutorial:
http://www.gametutorial.net/
You might take a variable like flag and set its value to 1 when hero's turn and its value to 0 when villan's turn
if(flag==1)
{
villans turn;
flag=0;
}
else if(flag==0)
{
heros turn;
flag=1;
}
This works

method does not override or implement a method from a supertype error

I'm trying to design an undo/redo mechanism to my Chess game.. I decided to use stack data structure which is going to build on an ArrayList.. I also want that my UndoStack and RedoStack classes should be singleton.. However i'm getting
method does not override or implement a method from a supertype
pop() in UndoStack cannot implement pop() in IStackable
return type Move is not compatible with cgas5.Move
where Move is a type-variable:
Move extends Object declared in class UndoStack
error..
Here is my IStackable interface:
package cgas5;
public interface IStackable {
abstract public Move pop();
abstract public void push(Move m);
}
and my UndoStack class
package cgas5;
import java.util.ArrayList;
public class UndoStack<Move> extends ArrayList<Move> implements IStackable {
UndoStack undoStack;
private UndoStack() {
undoStack = new UndoStack();
}
public UndoStack getUndoStack() {
if (undoStack == null) {
undoStack = new UndoStack();
}
return undoStack;
}
#Override
public Move pop() {
Move m = get(size() - 1);
remove(size() - 1);
return m;
}
#Override
public void push(Move m) {
add(m);
}
}
and if it's necessary my Move class:
package cgas5;
public class Move {
private Piece pieceToMove;
private Square currentSquare;
private Square targetSquare;
private Piece capturedPiece;
private Piece promotedPiece;
public Move(){
}
public Move(Piece pieceToMove, Square currentSquare, Square targetSquare){
this.pieceToMove = pieceToMove;
this.currentSquare = currentSquare;
this.targetSquare = targetSquare;
}
public Piece getPieceToMove() {
return pieceToMove;
}
public void setPieceToMove(Piece pieceToMove) {
this.pieceToMove = pieceToMove;
}
public Square getCurrentSquare() {
return currentSquare;
}
public void setCurrentSquare(Square currentSquare) {
this.currentSquare = currentSquare;
}
public Square getTargetSquare() {
return targetSquare;
}
public void setTargetSquare(Square targetSquare) {
this.targetSquare = targetSquare;
}
public Piece getCapturedPiece() {
return capturedPiece;
}
public void setCapturedPiece(Piece capturedPiece) {
this.capturedPiece = capturedPiece;
}
public Piece getPromotedPiece() {
return promotedPiece;
}
public void setPromotedPiece(Piece promotedPiece) {
this.promotedPiece = promotedPiece;
}
}
Thanks in advance..
This is the problem:
public class UndoStack<Move> extends ArrayList<Move>
That's using Move as a generic type parameter, whereas really you don't want a generic type at all - you just want to use Move as the type argument for ArrayList<E>. You want:
public class UndoStack extends ArrayList<Move>
That should fix the problem - although personally I'd strongly recommend using composition instead of inheritance here. (In other words, make your UndoStack type contain an ArrayList<Move> - or something similar - rather than subclassing it.)
Additionally, this is never going to work:
UndoStack undoStack;
private UndoStack() {
undoStack = new UndoStack();
}
That means that to create an UndoStack, you need to create another UndoStack... how do you expect that to happen? You'll currently get a stack overflow exception... why do you need the variable at all?

representing different kind of players in a class [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I am writing a class to represent cricket players. There are four types of cricket players
1 wicket player
2 batsman
3 bowler
4 allrounder
I'm not sure if I am representing the players in the right way
public class Player {
final static int WICKETPLAYER=1;
final static int BATSMAN=2;
final static int BOWLER=3;
final static int ALLROUNDER=4;
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public String whatTypeOFplayer(){
switch(playertype){
case WICKETPLAYER:
return "wicketplayer" ;
case BATSMAN:
return " batsman";
case BOWLER:
return "bowler";
case ALLROUNDER:
return "allrounder";
default:
return "error";
}
}
}
First of all, you should use enums to represent the player types instead of ints, like
enum PlayerType {
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER
}
Then you could use the name() method to get a string representation of the PlayerType.
If there's more to the player types that just the name (e.g. different behaviour, methods etc.), you might consider creating subclasses of Player, like class WicketPlayer extends Player.
A third way would be to use composition and add components like PlayerBehaviour etc. to the basic player class.
I terms of complexity, I'd say no. 1 is the easiest, whereas no. 3 might be too complex for you right now. So you might try and either use no. 1 or no. 2, depending on your requirements.
You are likely to be better off with an enum and an EnumSet.
public Role {
WICKET_KEEPER, BATSMAN, BOWLER, FIELDER
}
public static final Set<Role> ALL_ROUNDER = EnumSet.allOf(Role.class);
private final EnumSet<Role> roles;
private Role position;
public Player(EnumSet<Role> roles) { this.role = roles; }
public void setPosition(Role role) { this.position = role; }
public String whatTypeOFplayer(){
return roles.equals(ALL_ROUNDER) ? "allrounder" : roles.toString();
}
BTW Its a Wicket Keeper not a Wicket Player http://www.cricketscotland.com/system/files/images/13_13.jpg
A better way is to inherit from the class Player, it will allow you a simpler treatment for each player and different behaviors for common actions. for example:
Player.java
public class Player {
int currentbatting;
int bowlerbating;
int playertype;
public Player(int i,int currentbatting){
this.currentbatting=currentbatting;
playertype=i;
}
public abstract String whatTypeOFplayer() {
return playertype;
}
}
WicketPlayer.java
public WicketPlayer extends Player {
public WicketPlayer(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "wicketplayer";
}
}
Batsman.java
public Batsman extends Player {
public Batsman(int i,int currentbatting){
super(int i,int currentbatting);
playertype = "batsman";
}
}
And so on.
use Java Enums: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
In this case - and because I smell homework - you should use one base class Player and a subclass for each player type.
Example:
public abstract class Player {
// some attributes and methods all players share
public abstract String whatTypeOfPlayer();
}
public WicketPlayer extends Player {
#Override
public String whatTypeOfPlayer() {
return "Wicket Player";
}
}
Bonus - then I'd use a factory to create players:
public PlayerFactory {
enum PlayerType {WICKETPLAYER, BATSMAN, BOWLER, ALLROUNDER}
public static Player createPlayer(PlayerType type, String name) {
switch(type) {
case WICKETPLAYER : return new WicketPlayer(name);
//...
}
}
}
If you are using Java 5+ use Enum Types Java Enum Types. According to Effective Java it's not a good practice to use a bunch of constants, instead use Enum.
public class Player {
public enum Role{
WICKETPLAYER,
BATSMAN,
BOWLER,
ALLROUNDER;
}
final int currentbatting;
final Role playerRole;
public Player(final Role role, final int currentbatting){
this.currentbatting=currentbatting;
this.playerRole=role;
}
public String whatTypeOFplayer(){
return this.playerRole.toString();
}
}

Categories