What is the difference between coding to interface and dependency injection. could you please explain it with an example?
jeudi 31 mars 2016
How to merge base class dataset with derived class dataset
In my project I have hierarchy of classes which implements custom properties. Here is simplified version for the console application.
class Program
{
static void Main(string[] args)
{
BaseClass base_ = new BaseClass();
DerivedClass derived_ = new DerivedClass();
Console.WriteLine(base_.ToString());
Console.WriteLine(derived_.ToString());
Console.ReadLine();
}
}
class Property
{
string key;
string value;
public Property(string key, string value)
{
this.key = key;
this.value = value;
}
public override string ToString()
{
return "(key=" + key + ": value=" + value + ")";
}
}
public struct PropertyConfig
{
public string key;
public string defaultValue;
}
class BaseClass
{
Dictionary<string, Property> properties = new Dictionary<string, Property>();
protected virtual PropertyConfig[] classPropertyConfig
{
get
{
return new PropertyConfig[]
{
new PropertyConfig() { key = "p1", defaultValue = "v1" },
new PropertyConfig() { key = "p2", defaultValue = "v2" }
};
}
}
public BaseClass()
{
initProperties(classPropertyConfig);
}
void initProperties(PropertyConfig[] configs)
{
foreach (PropertyConfig config in configs)
{
properties.Add(config.key, new Property(config.key, config.defaultValue));
}
}
public override string ToString()
{
return GetType().Name + ".Properties: " + string.Join(",", properties.Select(kvp => kvp.Value.ToString()).ToArray());
}
}
class DerivedClass : BaseClass
{
protected override PropertyConfig[] classPropertyConfig
{
get
{
return new PropertyConfig[]
{
new PropertyConfig() { key = "p2", defaultValue = "update" },
new PropertyConfig() { key = "p3", defaultValue = "v3" }
};
}
}
public DerivedClass(): base()
{
}
}
Base class defines a configuration of its property objects in the array which is overridden in the derived class.
the resulting output is below and it is correct. But it is not what I need.
BaseClass.Properties: (key=p1: value=v1),(key=p2: value=v2)
DerivedClass.Properties: (key=p2: value=update),(key=p3: value=v3)
What I need basically to be able to merge configs from base and derived classes in order to get this
BaseClass.Properties: (key=p1: value=v1),(key=p2: value=v2)
DerivedClass.Properties: (key=p1: value=v1), (key=p2: value=update),(key=p3: value=v3)
Ideal solution must allow to set just configuration in the derived class and nothing more.
Using standard evaluation and do_ to run simulations on a grid of parameters without do.call
Goals
I want to use dplyr to run simulations on grids of parameters. Specifically, I'd like a function that I can use in another program that
- gets passed a data.frame
- for every row calculates some simulation using each column as an argument
- also is passed some extra data (e.g., initial conditions)
Here's my approach
require(dplyr)
require(lazyeval)
run <- function(data, fun, fixed_parameters, ...) {
fixed_parameters <- as.environment(fixed_parameters)
data %>%
rowwise %>%
do_(interp( ~ do.call(fun, c(., fixed_parameters, ...))))
}
This works. For example, for
growth <- function(n, r, K, b) {
# some dynamical simulation
# this is an obviously-inefficient way to do this ;)
n + r - exp(n) / K - b - rnorm(1, 0, 0.1)
}
growth_runner <- function(r, K, b, ic, ...) {
# a wrapper to run the simulation with some fixed values
n0 = ic$N0
T = ic$T
reps = ic$reps
data.frame(n_final = replicate(reps, {for(t in 1:T) {
n0 <- growth(n0, r, K, b)
};
n0})
)
}
I can define and run,
data <- expand.grid(b = seq(0.01, 0.5, length.out=10),
K = exp(seq(0.1, 5, length.out=10)),
r = seq(0.5, 3.5, length.out=10))
initial_data = list(N0=0.9, T=5, reps=20)
output <- run(data, growth_runner, initial_data)
Question
Even though this seems to work, I wonder if there's a way to do it without do.call
.
Notes and References
- this question on do.call and standard evaluation in dplyr is helpful, but I'm looking for a way to avoid do.call if possible
- dplyr's nse vignette was helpful in writing this; and makes me think
.values
could work in place ofdo.call
Replacing a singleton solution for a memory manager in C++
I have in my project two classes for managing memory: MemoryStorage
and MemoryFile
.
The first works similar to a HDD and keeps MemoryFiles
(files, directories, etc.) by using a singleton (add, remove, free, etc). The second works like fstream
, but for memory (open, close, write, read, etc.).
Use Example
MemoryFile file(&MemoryStorage);
// Open file in write mode
if (file.open("filename", open_mode::out)) {
// Data file
int* obj = new int;
*obj = 0;
// Write in internal buff
file.write(obj, sizeof(int));
delete obj;
// Put buff in MemoryStorage and clear buff
file.close();
}
// Other moment
// Open file in read mode
if (file.open("filename", open_mode::in)) {
// Data file
int* obj = new int;
// Write in internal buff
file.read(obj, sizeof(int));
cout << *obj << endl; // Print: 0
delete obj;
// Put buff in MemoryStorage and clear buff
file.close();
}
If I don't use a singleton, creating files with the same name in memory will be possible, leading to an inconsistent file system.
I've read several articles in stack overflow like this one that talk about how singleton is bad pattern according to many programmers.
How else do I resolve the programming problem above without a singleton pattern? Do I use a private static member in MemoryStorage
that replicates the effect of a singleton?
Prototype pattern in C++
I read about the Prototype Pattern
and I think I pretty much understand it. But I need some real example for this pattern to fully understand. In all examples I saw a copy constructor
and new
in the clone()
function to create a new object from an already existing one. All the descriptions say that this pattern is more efficient. It is also creates a new object using the new
operator.
But how is it more efficient ?
Or when shall I use this ? When could it be more efficient ?
Non-linear pipelining of generators in Python
I would like to write a data processing toolbox following the pipeline pattern.
Because two elements Process1
and Process2
of the pipeline could make use of the same data from the DataGenerator
(non-linear pipeline), I created an element DataProcessor
consuming the generator created in DataGenerator
and executing the different processes.
I am not really happy with that because some subsequent element only needing data processed by one of Process1
or Process2
should wait for both to be executed.
I am not an expert in design pattern, so maybe I'm using the wrong pattern for my task.
Any suggestion?
class DataGenerator:
"""
Dummy data generator
"""
def __init__(self, size):
self.size = size
def execute(self):
for i in range(1000):
yield numpy.random.random((self.size))
class Process1:
"""
Some process
"""
def __init__(self, config):
self.config = config
# not used
def execute(self, frames):
for frame in frames:
yield self.process(frame)
def process(self, frame):
# process data
return processed_frame
class Process2:
"""
Some process
"""
def __init__(self, config):
self.config = config
# not used
def execute(self, frames):
for frame in frames:
yield self.process(frame)
def process(self, frame):
# process data
return processed_frame
class DataProcessor:
"""
Execute all processes
"""
processes = []
def add_process(self, process_instance):
self.processes.append(process_instance)
def execute(self, frames):
for frame in frames:
processed_frame = []
for p in self.processes:
processed_frame.append(p.process(frame))
yield processed_frame
Design pattern for retrofit interface
I have trouble with the design of my Retrofit interface creator. I want to be able to instanciate the API interface in a generic way and update the corresponding instance whenever a token is passed. Currently, when I update the token, I have to call createService() method again to get the new instance that used the token in the generation of the Interface...
Somebody asked for a similar question but never got an answer here
public class RetrofitCreator {
private static String TAG = "RetrofitCreator";
private static String WSSE = null;
private static String AmzToken = null;
static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
private static AmazonAPI amazonAPI = null;
private static VanishAPI cobaltAPI = null;
//static OkHttpClient client = new OkHttpClient.Builder().build();
static OkHttpClient.Builder httpClient = new OkHttpClient.Builder().addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY));
private static Retrofit.Builder builder =
new Retrofit.Builder();
public static <S> S createService(Class<S> serviceClass) {
S mAPI = null;
if(serviceClass.getSimpleName().equals("VanishAPI")){
if(VanishAPI==null){
VanishAPI = (VanishAPI) createVanishAPI(serviceClass);
}
mAPI = (S) VanishAPI;
}else if(serviceClass.getSimpleName().equals("AmazonAPI")){
if(amazonAPI==null){
amazonAPI = (AmazonAPI) createAmazonAPI(serviceClass);
}
mAPI = (S) amazonAPI;
}
return mAPI;
}
public static void setWSSE(String WSSE) {
RetrofitCreator.WSSE = WSSE;
vanishAPI = createVanishAPI(VanishAPI.class);
}
public static void setAmzToken(String token) {
RetrofitCreator.AmzToken = token;
amazonAPI = createAmazonAPI(AmazonAPI.class);
}
private static <S> S createAmazonAPI(Class<S> serviceClass){
httpClient = getUnsafeOkHttpClient();
builder = new Retrofit.Builder()
.baseUrl(Constants.URL_AMAZON)
.addConverterFactory(JacksonConverterFactory.create());
if (AmzToken != null) {
Log.w(TAG, "WSSE not null!");
Interceptor interceptorSecure = new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Cache-Control", "no-cache")
.header("Accept", "application/json")
.header("Authorization", "Bearer " + AmzToken)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
};
httpClient.addInterceptor(interceptorSecure);
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
(...)
}
To get it in each Activity I use :
amazonApi = RetrofitCreator.createService(AmazonAPI.class);
What is the name of the of/from constructor pattern found in the java.time package? [duplicate]
This question already has an answer here:
- What are static factory methods in Java? 14 answers
I recently picked up Java and I was exploring the java.time
package and noticed a, in my view, very nice interface where I could do ZonedDateTime.of(2015, 12, 1, …)
. Instead of the classical new ZonedDateTime(2015, 12, 1, …)
. I saw the same with a .from
method to create the object from another object.
But just looking at the implementation without understanding why it's sometimes of
and sometimes from
I feel that I'm missing something. Especially since I'm now keen on using the same pattern for some of my own classes.
This being Java I'm assuming that there's an actual formal proper name for this, and not just something that the implementors of the java.time
package made on their own. :)
Refactoring of a custom case of validation
I have a hierarchy of classes for validation and i'm at a point that i'd like to refactor (if possible and useful) leaving the code decoupled.
public class DefaultValidation : ValidationList
{
public DefaultValidation(Cutomer customer, Dto dto)
{
DefaultRepository repository = new DefaultRepository();
EntityBook entityBook = (EntityBook)repository.GetBookById(dto.IdBook);
this.Add(new BookMustBeValidValidation(entityBook));
EntityVideo entityVideo = (EntityVideo)repository.GetVideoById(dto.IdVideo);
this.Add(new VideoValidation(entityTask));
this.Add(new OtherNecessaryValidation(dto.OtherProperty));
}
}
This class is a concrete for validation. I add all the rules in a list so i can add various kind of validation in form of classes.
(I used this method that seemed interesting)
The need of a refactory comes when i add another similar class:
public class SpecialValidation : ValidationList
{
public SpecialValidation(Cliente cliente, DtoRichiesta richiesta)
{
this.Add(new OtherNecessaryValidation(dto.OtherProperty));
this.Add(new SpecialAnotherOneValidation(dto.AnotherProperty));
}
}
The root is in common, the difference is what classes (rules) i inject to the list. Do you think something should be changed?
Thanks
Should we design interfaces to include object manipulators
I have a class named ValidationResult
which implements IValidationReport
. These are generic entities which are meant to encapsulates output of the various validators we have. All validators do return IValidationReport
.
As a standard design practice we include only getters in IValidationReport
, and no setters or methods that can manipulate the contents of the returned object. Thus it has getResult(String filePath)
, getMessages(String filePath)
etc. which returns validation result, validation messages and other information of validation of the specified file.
ValidationReport
have different overloads of the form addResult(filePath, message, ...)
which adds the corresponding information against specified filePath
. However we also have one method in ValidationReport
called addResult(IValidationReport)
. This method essentially work as merging two ValidationReport
s. So if two validation reports (the on which this method is called and the one which is passed as an argument) have validation information of same file, then it will be merged.
Now in one of our modules, it happens that we are calling two validators. Both have validate()
methods which returns IValidationReport
. However I cannot merge the two as IValidationReport
contains only getters, but addResult(IValidationReport)
. That is following:
IValidationReport valrep1 = validator1.validate();
IValidationReport valrep2 = validator2.validate();
valrep1.addResult(valrep2); //cannot do this as valrep1 is IValidationReport and it does not contain addResult(IValidationReport)
- So what should I do? Should I be adding
addResult(IValidationReport)
toIValidationReport
. But then it will break design convention of not adding object manipulators to interfaces. - Where did I go bad with the design? Or am I missing something?
What's the best practice when an AngularJS directive has a lot of bindings in its isolated scope?
Suppose each card-item directive needs to know a lot of outside contexts and acts accordingly.
We could make a service to monitor the outside world, and inject the service into card-item directive, like:
scope: {
item: '=',
service: '=',
}
<card-item item="card"
service="ItemService">
</card-item>
This seems like a bad practice, because the directive knows too much about the service (e.g. calls the service's functions inside directive).
Many posts about AngularJS best practices suggest isolation, like following.
But it still doesn't feel right here:
scope: {
item: '=',
isSelected: '&',
inSelectMode: '&',
inMoldMode: '&',
onToggleSelect: '&',
onTogglePreview: '&',
onToggleSort: '&',
onDelete: '&',
isPreviewing: '&',
isSorting: '&',
locales: '=',
printUrl: '=',
}
<card-item item="card"
is-selected="ItemService.isSelected(card)"
in-select-mode="ItemService.inSelectMode()"
in-mold-mode="ItemService.inMoldMode()"
on-toggle-select="ItemService.toggleSelect(card)"
on-toggle-preview="ItemService.togglePreview(card)"
on-toggle-sort="ItemService.toggleSortMode()"
on-delete="ItemService.removeParticle(card)"
is-previewing="card === entityInPreview"
is-sorting="ItemService.inSortMode()"
locales='LocaleService.currentLocales'
print-url="getPrintUrl(card)">
</card-item>
What's your suggestion?
Thanks for reading.
Implementing a command queue in C#
I'm making a backup system and dealing with the fact System.FileWatcher is raising multiple events per change (copying a file raises Created and Changed, for one) by queueing the commands.
Right now, I'm subscribing to events:
watcher.Changed += new FileSystemEventHandler(OnChanged);
and creating an object of a class:
private void OnChanged(object sender, FileSystemEventArgs e)
{
var now = DateTime.Now;
var change = new ChangeCommand(now, _fileLogPath, e.FullPath);
}
ChangeCommand is a class that implements the ICommand interface. My question is how and when to actually enqueue them. Since trying to access a file that is being accessed would throw an exception, I want to keep Peek-ing until it doesn't and then Dequeue.
Approach for flag based process [on hold]
background
I have multiple attributes for user. Based on the attribute I do certain alteration to client request.
The problem
I have many such attributes which impacts alteration of client request. As of now I am maintaining it in SQL table. Because of this my code looks clumsy.
My question
what is the best approach for solving the problem ? is there any design pattern for that?
Refactoring across multiple applications
this question is more of an investigation for finding a solution question and not implementation. OK, so i need to find a solution that will manage an entity across multiple applications. The current behavior is this when an employee leaves the company it is still kept it the DB's of all applications (all of our applications are internal). He/She however is at some point deleted from the Active Directory. I need to find a way/ solution that can be applied to all applications that will manage the ex-employee (basically erase him/here from all of the DB's where appears).
I thought of the following solutions :
Another solution would be the following Create files(XML, txt, whatever) based on User Info Tables for all DBs - this file will contain both active and inactive users Create a file from the AD (XML, txt, whatever) this file of course will contain active users
Using the AD file compare it with all other files best if we could use parallel programming here, access the AD file at the same time with all other files. The structure of the files should be simple and similar - only needed infos required to be contained.
2nd
Create a DB with one table Create the table that stores all user information (this is taken from AD) The schema of the user info table should be simple
ID | AccountName | DisplayName | Email | IsActive(NULL) | IsGrupeCreate a task that manages this user information table (updates the table when the AD is changed) Create a triggering mechanism when a modification in the User table occur this will trigger an event across all databases that have user info related logic.
On a positive note: - not to hard to implement (if clear separation is needed then a console application will be created, separated of all other projects this console application will handle the logic to maintain the UserInfo table up to date - this is just an example)
On a not so good side: - the triggering mechanism i think it's going to be quite large and complicated since all DB's have different schema so it will be needed to be taken into consideration the relations betweens one DB entities
EX: UserApplication TBL: ID | appId(FK) | userID(FK)
the deletion of the entity (app or user with specific ID) will need to also handle the deletion of the UserApplication entity that refers that specific entity with that specific FK, but keep the other dependent entity within the DB
3rd
Create a new app / services that manages User related logic in this case the deletion/ insertion/ update. The idea behind the application is this.
The first time the application will run, it will populate the User Table with all AD's users
The schema of the user info table should be simple
ID | AccountName | DisplayName | Email | IsActive | IsGrupeAfter the first run every time a new user is inserted, deleted, updated this will reflect in the table as well. If a user is deleted it will be put in a state of 0 on the IsActive field.
After all the business logic that manages the user table is done, we could use the webapi across all applications (of course only application that have user business related to them). This way a single UserInfo tbl is shared across multiple apps.
Down sides: - Complicated, Time consuming, Hard to implement - Massive architectural change across many applications, since UserInfo related entities and tables will not be needed. - Massive changes over the implementation.
On a positive note: - Depending on the direction that the project is going: 1. Either having one task to update the User Information table using the Active Directory. 2. Or somehow chain also the newly created app with the app that manages the active directory (any change related to a user should translate in changes over the User Info table), in which case there is no task needed the process becomes automatic.(at least i think it should) An event changing the AD will translate in a service being called (from the new webapi) depending that event -> -> lets say Delete -> the table will be updated (meaning i thing better to set the IsActive state but keep the user as well) , this will result in changes over all of the applications that use the User Info table - We could start using SOLID : Dependency Injection, Inversion of Control, and also refactoring the code (of course if have time and approved)
So this is what i could come up with, any ideas, better solutions, would be very helpful. Thank you
How to get rid of the inheritance?
I have an algorithm, and I have 2 different implementations of the algorithm. These implementations should be called from many places, depending on the mode selected by the user. I wouldn't like to write conditional statements at all places where implementations called. So, I create an abstract class and Implementations inherit it. I can set the desired mode in one place like this:
if(firstMode){
list = new ListForm1();
}
else{
list = new LiastForm2();
}
And after that in all other places I can enjoy all the benefits of polymorphism. It works good but I want to get rid of the inheritance of the following reasons:
- I heard that composition is much better than inheritance.
- The first form of the algorith is much easier then the second form. In the first form I have only 3 methods and in second form I have 15 methods. The abstract class had to include all 15 (and 5 common methods). It turns out that the 12 methods not using by the first form.
- Theoretically, there may be a new form of the algorithm, which will have even less in common with the other two, but it will bring 10 new methods and all of them will have to add an abstract class.
The Strategy Pattern, as I understand, does not make sense to use here. Here is the example of Strategy Pattern:
//abstract strategy
interface Strategy {
int execute(int a, int b);
}
// concrete strategy1
class ConcreteStrategyAdd implements Strategy {
public int execute(int a, int b) {
return a + b;
}
}
// concrete strategy2
class ConcreteStrategySubtract implements Strategy {
public int execute(int a, int b) {
return a - b;
}
}
//concrete strategy3
class ConcreteStrategyMultiply implements Strategy {
public int execute(int a, int b) {
return a * b;
}
}
class Context {
private Strategy strategy;
public Context() {
}
// Set new concrete strategy
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
// use strategy
public int executeStrategy(int a, int b) {
return strategy.execute(a, b);
}
}
It has the same problems. Strategies should be linked with each other. If I link them with the interface instead of an abstract class it will be even worse. Interface will contain a lot of methods but many of them will not be needed for the first form of the algorithm. In addition, general methods have to duplicate in all concrete strategies. I can not provide a default implementation in the interface.
Moreever, I don't understand how to use composition here. As I understand, Strategy Pattern already used composition. Class Context includes the instance of Strategy as a field. But maybe it is delegation.
So, here is my question:
Can I get rid of all the above problems (too many methods of an abstract class, the strong connection, because of which it will be difficult to add a new form of an algorithm), but still use conditional statements in only one place, not in all cases when I need some form of algorithm.
Design pattern for a data access layer
I had to write a data access layer in a certain java project to support both nosql and SQL db severs.
To use it you need to configure which db server you're using and use the business logic layer which uses the DAL behind the scenes.
I wrote a basic DAO interface for the basic operations such as remove update and so on.
For the BL layer I wrote abstract classes using the basic interface which would receive it from a DAO factory. You needed to get those classes from another factory handling the BL instances.
Things were getting more complicated and the code turned to boilerplate when I needed more complex queries for the db which each one needed to be implemented separately and then I needed to check and cast the type of the DAO to use the methods hidden by the basic interface. This resulted in many classes for only one model object.
TL;DR I need a simple and scalable way to handle objects with a single API when the db type isn't known until run-time.
My question is whether there is better way to handle this problem? Maybe some design pattern I'm not familiar of which could be nice.
Thank you!
How to allow Object creation of a class on only particular classes in PHP?
In PHP, let there be four classes A, B, C, and D. None of them inherits the other. They are all independent classes. Now, I want only B and C to be able to create Objects of the class A. D Should not be able to create the Object of class A.
Can this be done in PHP? If So, how? I tried refreshing my object oriented concepts, but can't seem to find an appropriate answer in PHP.
Little help would be much appreciated.
mercredi 30 mars 2016
Update data that comes from server frequently without running all over the fields every time
I'm getting every few seconds an Object
from my Server with some data, lets say it's a level game data, that includes : title , second_title , score, playerRank etc.
At first time I draw and update all that information in the right places but when update come I sometimes have change in only one parameter, for example in title
and sometimes it's coming without any changes.
What I do is in every updadte I run on all the object fields and check:
if (title != object.title) {
updateTitle (object.title);
}
if (score != object.score) {
updateScore(object.score);
}
if (second_title != object.second_title) {
updateSecondTitle (object.second_title);
}
and so on...
I think its not very useful in every update run on all the fields for that update again and again, any ideas or some kind of design pattern to do it more flexible.
Multi version Api Architecture
All
I had design a multi version API architecture, Please give me feedback and suggestion about good and bad, or there are better way to achieve this.
- version server (MVC4) to route request to correct API interface(WebApi).
- version will send to server by header, will default to 1.0 if not header found.
First time I design for multi version API architecture, and google does't have much information for this.
Operating maintenance on Services via a scheduler Conception and implementation issue
This is the Service abstract class (I don't want to force the user to redefine terminate and initialize):
package schedule;
public abstract class Service {
public abstract String getReferer ();
public static void terminate () {
}
public static void initialize() {
}
}
I'm making a Scheduler to operate treatment on a whole set of Services it has stored.
Scheduler is a Service, and it is an observer, and every Service is a Singleton.
Without talking about Singletons (I have already seen StackOverFlow mad over these, but I need a pool of classes with single controlled access) is it a bad idea to try to store types ? In that way, i could make something like
Set<Class<? extends Service>> servicePool; // defined in the ctor as a TreeSet
public static void initialize () {
if (instance == null)
throw new CustomException("Ill-initialised Scheduler");
for (<? extends Service> S : instance.servicePool)
S.initialize(); // static function called on S as a class.
}
Would that be a bad thing ? and Why ? Else, How to do it ? Maybe I shouldn't put initialize (and terminate) static in Scheduler, but it would mean to either stop it from being a Service (which is wrong, semantically) or to make initialize instance-dependant, which would lose all the interest of this Service thing.
Moreover, I will likely run lots of dead code (for the Services which didn't (for instance) redefined terminate (). Is there a way to test if (function is redefeined) then run function
?
create class dynamically in c# from a list of string [duplicate]
This question already has an answer here:
I have a list of string which would have a different event type names. The code is given below,
public class Main
{
public void Run()
{
List<string> classList = new List<string>
{
"Event_one",
"Event_two"
};
foreach (string item in classList)
{
IEvent ent;
switch (item)
{
case "Event_one":
ent = new EventOne();
ent.HandlEvent();
break;
case "Event_two":
ent = new EventTwo();
ent.HandlEvent();
break;
}
}
}
}
public class EventOne : IEvent
{
public void HandlEvent()
{
throw new NotImplementedException();
}
}
public class EventTwo : IEvent
{
public void HandlEvent()
{
throw new NotImplementedException();
}
}
public interface IEvent
{
void HandlEvent();
}
How can I remove the switch statement and make the code more loosely coupled?. My code sits inside the website/app_code.
Returning an interface object from a method without instantiating an (unknown) concrete type
I'm sure there's some solution or pattern to this but i'm having trouble articulating the question to find the right answer.
I have an interface, ICar:
public interface ICar {
void SetMake(String make);
String GetMake();
}
I have a class, Car:
public class Car implements ICar {
private String make;
public void SetMake(String make) { this.make = make; }
public String GetMake() { return make; }
And I have a method in another class, which does not know about Car. In the spirit of polymorphism I'd like this method to return an ICar, so that someone could create their own implementation of ICar and utilize the method for their car:
...//class preamble
public ICar myMethod() {
ICar myCar = new ICar();
myCar.SetMake("Ferrari");
return myCar;
}
I'm not sure why something like this can't work. As ICar contains the method SetMake, every implementation must also contain this method. Surely the jvm could in some way queue up the method calls and then run them when a concretion of the methods is available?
Another idea would be to pass a newly created implementation of ICar as a parameter to myMethod and call its methods, but I feel like this may not be such a clean implementation, as I would need to create an instance of Car each time. Also if there is no parameter-less constructor, i would have to instantiate it with dummy data (also not clean).
I feel like i'm lacking some understanding to see how to implement something like this, and was wondering if anyone might be able to help?
Thanks.
TCP Server - Multi User File Upload
I'm struggling with trying to figure out how to implement a TCP server in python. I currently have a TCP server that can connect to one client at a time. The Client can successfully communicate with the server, and upload a file using a single socket. Currently, it is single threaded and when one Client connects it blocks the other clients from connecting until it is done.
I'm struggling with the design portion on making this multi-client friendly. If I'm uploading files concurrently should there be multiple sockets? If I go with one socket, how do I differentiate data from different clients?
Can anyone give some advice on this?
What Cloneable do in java?
i am trying to study design patterns and study prototype design pattern what Cloneble do and why clone call super () and how creating duplicate object while keeping performance in mind ?
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
Which design pattern is recommended when implementations only differ in a single method?
I have an interface with 6 methods used to manage datasets. The only method that differs between implementations is getSerializedVersion()
and the constructor that is able to parse the serialization string.
public interface DataSets {
public void addEntry(...);
public void removeEntry(...);
public void manipulateEntry(...);
public SomeType getEntry(...);
public List<SomeType> getAllEntries();
// This differs:
public String getSerializedVersion()
}
I can't change the Interface.
My first idea was to generate an abstract class and implement the first five methods. For the concrete implementations (e.g. DataSetsXML
, DataSetsYAML
, ...) I only have to implement getSerializedVersion()
and the constructor that that is able to read the String and initialize the object.
To make it more testable a different design might be better (http://ift.tt/1qiSOk1) but which one?
Answers might be subjective, but I think there are some general rules or a least (objective) advantages and disadvantages of the different approaches,...
Is an application-level controller acceptable in Angular when used for constants?
I am creating an application that has a lot of interacting sub-components. Many of the different views display some of the same data in summary format. The data that is retrieved from the REST calls returns codes, and I need to do lookups for those codes. I want to create an application-level controller to hold all the code-translate objects (constants) used everywhere. Would this follow best practices?
Something along the lines of below. So the main body will have the "appCtrl" that houses the constants built off web-services, and then the different includes can reference them as children of the parent controller.
index.html
<body>
<div data-ng-controller="appCtrl" class="container-fluid">
<div data-ng-include data-src="'navigation/navigation.html'"></div>
<div id="mainContent" data-ng-view></div>
<div id="versionTag">
APP: v<span data-app-version></span>
</div>
</div>
</body>
navigation.html
<div data-ng-controller="aumNavigationCtrl">
.
.
.
</div>
app.js (this is truncated to give you an idea)
.controller('appCtrl', ['$scope','Tasks',
function($scope, Tasks)
{
//define task types to use in app
$scope.taskTypes = [];
Tasks.getTypes({},{}).$promise.then(
function(data)
{
for (var i = 0; i < data.length; i++)
{
$scope.taskTypes[i] =
{
"code": data[i].code,
"description": data[i].description
};
}
});
});
navigation.js (again, truncated for brevity)
.controller('aumNavigationCtrl', ['$scope',
function($scope)
{
$scope.getTypeDescrip = function(typeCode)
{
for (var i = 0; i < $scope.taskTypes.length; i++)
{
if (typeCode === $scope.taskTypes[i].code)
{
$scope.typeDescrip = $scope.taskTypes[i].description;
}
}
}
});
In MVC, View has both interface MC, how to restrict the view directly call the model APIs?
I recently came across Kathy Sierra - HeadFirstDesignPattern -JAVA. I have doubt regarding MVC. View has both MC interface references.But view using the controller interface API's to update the data.this controller calls the Model API and notify the view to update.
Since View has model interface , i can directly call the Model api and violate the principal of updating via controller.How to enforce the view to use controller only.
no enough info from this post : Controller in MVC design pattern
Design patterns one to many and left outer join
I've got two tables, and, of course, 2 JavaBeans.
Table A
id name desc
1 John Malcom
2 Steve Jobs
3 Mark The Best
Table B
id thing fk_A_id (many to one)
1 Bag 1
2 Pet 1
3 Ball 2
In java I have this classes:
class A {
private int id;
private String name, desc;
private List<B> bList;
//getters and setters
}
class B {
private int id;
private String thing;
private int fkA;
}
I have to do a DAO which obtain data from these tables. In the view I have to show data like a sql left outer join between A and B tables, which returns a JSON object, something like this
Aid Aname Adesc Bthing
1 John Malcom Bag
1 John Malcom Pet
2 Steve Jobs Ball
3 Mark The Best null
This data will be shown through a boostrap-datatable, and my Controler would populate it as a plain json object.
How do you build the DAO/JavaBeans to solve it? I think the best option is creating an utility class which transform, the List objects in this plain json, which does not alter the basic structure of the model, but a partner has suggested other solution.
Best design pattern to open and parse file
I'm new at design patterns... I'd like to know if there was some design pattern to open and parse a text file. Thankyou!
Repository Design pattern
I have a question about Repository design pattern, exactly how to interact with many data sources.
For example, i have these repositories:
- UserRepositorySql
- UserRepositoryMongo
- UserRepositoryXml
(Is this even correct? i mean to create an repository for each data source?)
What is better:
-
An abstract class called UserRepository and the other ones extend from UserRepository.
-
Just an interface for these 3 Repositories.
Im not clear to how to retrieve an specific repository for an specific data source, if i use an abstract class, i could implement an UserFactory (factory pattern) class that returns me the specific repository object. (Is this even correct ?)
But how could i retrieve an specific repository if i use an interface? (Since factory pattern needs an parent abstract class, am i right?)
Also when i say "an specific repository" i mean receive a repository with its specific data source.
Thank you so much, redigaffi.
Repository Design pattern
I have a question about Repository design pattern, exactly how to interact with many data sources.
For example, i have these repositories:
- UserRepositorySql
- UserRepositoryMongo
- UserRepositoryXml
(Is this even correct? i mean to create an repository for each data source?)
What is better:
-
An abstract class called UserRepository and the other ones extend from UserRepository.
-
Just an interface for these 3 Repositories.
Im not clear to how to retrieve an specific repository for an specific data source, if i use an abstract class, i could implement an UserFactory (factory pattern) class that returns me the specific repository object. (Is this even correct ?)
But how could i retrieve an specific repository if i use an interface? (Since factory pattern needs an parent abstract class, am i right?)
Also when i say "an specific repository" i mean receive a repository with its specific data source.
Thank you so much, redigaffi.
How to make one method be called by some classes, but the rest could not?
There is one class named ClassA, it has one public function named FunctionA.
There is another class named ClassB, it needs to use FunctionA and it is not a subclass of ClassA.
The third one named ClassC, FunctionA should not be called by ClassC and it is not a subclass of ClassA.
In addition, the relationship between ClassB and ClassC is not inheritance.
If there are some solutions provided? or if there are suitable design patterns?
Thanks for help.
Best practices of implementing Repository and Unit of Work pattern in Android
I want to know if there is there any good sources for implementing the Repository and Unit of Work Patterns in android project , and is it a good practice to implement these patterns for projects other than .Net projects
weakreference vs eventbus to avoid memory leaks android?
I am developing an application in which I am using retrofit library for calling the web services . After calling web-service a callback return Response then I am passing the Response to the next activity. I want to know the best approach for this .
I am new in memory related problems please correct me if I am totally wrong.
Shall I make a new class then pass a weak reference to that class and call the function from that class on the main activity.
Or
I shall register a new event on event bus and when the callback returns the object ,fire the event and call the function.
Please consider what is good to avoid Memory Leaks.
What design pattern handles every combination of inherited classes?
I have an abstract class with a few inheriting classes that represent shapes and I would like to test for collisions. For now, here is my (Java) code:
public abstract class Shape {
public abstract boolean collision(Rectangle rectangle);
public abstract boolean collision(Circle circle);
}
public class Rectangle extends Shape {
// implementation of both abstract methods
}
public class Circle extends Shape {
// implementation of both abstract methods
}
I see the flaw in my code: I have to modify every class if I want to add another child class, say Triangle
.
I still would like to be certain that every collision is possible (Rectangle-Rectangle, Circle-Circle, Rectangle-Circle and Circle-Rectangle, plus the 5 more that Triangle would introduce, and so on).
Is there a design pattern that I haven't thought of that solves that problem nicely?
How can I inject Modules in Javascript?
I'm using Module pattern, now I wanted to know is that possible to inject one module into another like AngularJs.
Below is sample code that I've tried.
module.js
var AnotherModule = (function () {
function AnotherModule() {
this.anotherFunction = function () {
alert('Inside another Module');
}
}
return AnotherModule;
})(window);
var AnotherModule = new AnotherModule();
var Module = (function (window, AnotherModule) {
function Module(AnotherModule) {
var privateMethod = function() {
}
this.getName = function (brand) {
console.log('Inside get Name');
console.log(AnotherModule);
}
}
return Module;
})(window, AnotherModule);
var module = new Module();
module.getName();
mardi 29 mars 2016
What does template mean as a suffix of a class name?
In many programs, a Class with the suffix Template exists. For example, org.springframework.web.client.RestTemplate
, etc.
What does template mean as a class name suffix? Does it mean the Template Method pattern?
Do you know the reason?
Have a good day.
MVC pattern with AJAX calls
this is a weird question about a php mvc pattern with ajax calls, the purpose is make a better and dynamically web apps let me explain you:
when i learn php i used this pattern specifically :
model.php
<?php
class myClass {
private $attrOne;
private $attrTwo;
public function getAttrOne() {
return $this->attrOne;
}
public function setAttrOne($attrOne) {
$this->attrOne = $attrOne;
}
public function getAttrTwo() {
return $this->attrTwo;
}
public function setAttrTwo($attrTwo) {
$this->attrTwo = $attrTwo;
}
// ----------------------------------------------------
public function doSelect() {
//some code
}
public function doInsert() {
//some code
}
public function doUpdate() {
//some code
}
public function doDelete() {
//some code
}
}
controller.php
<?php
require "../models/model.php";
if(isset($_POST['action'])) {
$action = $_POST['action'];
if(is_callable($action)) {
$action();
}
}
function registerSomething(){
$model = new myClass();
$model->setAttrOne($_POST['attrOne']);
$model->setAttrTwo($_POST['attrTwo']);
$return = $model->doInsert();
echo $return;
}
function registerSomething2(){
// more app logic code and other stuff
}
view.php -> this is most a pure html file with php extension
<div id="result"></div>
<form id="register" role="form" >
<input type="text" id="attrOne" name="attrOne"/>
<input type="text" id="attrTwo" name="attrTwo"/>
</form>
<script src="script.js" type="text/javascript"></script>
And the script.JS
$('#register').submit(function() {
var action = 'registerSomething';
$.ajax({
data: $(this).serialize() + '&action='+action,
url: '../controlllers/controller.php',
type: 'POST',
success: function(response) {
$('#result').html(response);
}
})
return false;
})
so, what do you think about this pattern, is this pattern efficient? what is the best way to do ajax calls with a proper mvc pattern in php? is this a best practice?
i hope you can answer :)
thank you!
Sequantial pattern mining(cspade) using some transaction data
It is a problem for Sequantial pattern mining(cspade) using transaction data. Target for sequential pattern mining is sequenceID, eventID and item variables with crime_ dat data frame.
So, source dataset is in this format.
sequenceID eventID item
1 1 A
1 2 B
1 3 A
Before, I solved the problem using split function for association problem because using read.transactions func. is not reasonable for this case. # of split variable was just 2.
However, it is 3 for sequential pattern mining problem.
Can you give me some advaice to solve this?
Actually, I used this sentence to solve the problem using split function. Finally, it showed error.
crime.trans <- as(setNames(split(crime_dat, seq(nrow(crime_dat))), rownames(crime_dat))
+ ,"transactions");
===> Error in split.default(crime_dat, seq(nrow(crime_dat))) :
group length is 0, but data lenth is larger than 0
Logging best approach with CDI
Creating a new version of my RESTful service architecture using JEE 7, deploying to a Wildfly 9 instance, I was wondering if there is a clever way to create a log system, can you suggest some patterns? Thanks a lot.
Abstracting away DB Server type in C#/ADO.NET
C# / ADO.NET has:
SqlConnection / NpgsqlConnection / ...
SqlCommand / NpgsqlCommand / ...
SqlDataReader / NpgsqlDataReader / ...
...
This means that all of your DB code ends up being DB vendor specific. If you change DB vendors, you have to change all of your DB calls. And, you can't make your code DB vendor agnostic.
I don't mind creating DB vendor specific connections, but from that point forward, I want all of my DB calls to be generic, e.g. Command and DataReader.
I know I can do this by creating the Command and DataReader, etc. classes that can contain switch statements that call the appropriate vendor specific calls, but I'd prefer to do something a bit more elegant. I sense that one of the standard design patterns may help, but I've yet to find an elegant solution. Any help would sure be appreciated.
Acknowledgement to clients on asynchronous microservice
I read everywhere that service to service calls should be asynchronous in microservices. When the request has to pass through 2 or more async services, how can we do the client acknowledgement?
Here is my real time scenario. We are developing an email sending functionality in our organisation. We are planning to have 4 API services for this in the following order.
- Public API - exposing the email functionality to public
- Validation API - to validate the genuineness of the email and other fields
- Template fetching API - fetch the email templates from database/CMS and prepare the final content to be sent
- Email sending API - will receive the recipient and the email content
The problem is, we have to acknowledge the client who initiated the request with some id if successful, otherwise have to return the error code. If we have to adapt the best practice of making asynchronous service to service call, how we can acknowledge the client from Email sending API(final API)?
Hibernate 4 create sessionfactory in Abstract Factory (JEE)
I'm working in a web app (JEE) with Hibernate 4.2, I have the Abstract Factory Pattern implemented but for create the session factory I have not a init method because I use the first call to create the session factory to reuse in forward like a static, like you can see I get the session from the DAOImpl, to work and finally I close it. First I want to ask if this practice it's correct? Is there another better practice?
public class HibernateSessionFactory {
private static SessionFactory sessionFactory = buildSessionFactory();
private static final Logger logger = LogManager.getLogger(HibernateSessionFactory.class);
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sf = configuration.buildSessionFactory(sr);
return sf;
} catch (Exception ex) {
logger.error("Initial SessionFactory creation failed.", ex);
ex.printStackTrace();
throw ex;
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdownSessionFactory() {
sessionFactory.close();
}
}
DAOIMPL
public class RecordDAOImpl implements RecordDAO{.....
public String getRecord (Long id){
Session session = HibernateSessionFactory.getSessionFactory().openSession();
try {
session.beginTransaction();
.
.
.
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
} finally {
session.close();
}
return value;
}
DAO
public interface FieldDAO {.....
String getRecord (Long id);
Factory
public class HibernateFactoryDao extends DAOFactory {...
@Override
public RecordDAOImpl getRecordDAO() {
return new RecordDAOImpl();
}
Andorid Object Pool Pattern example
I've been reading many articles on how we can improve android app performance by reducing GC work of reclaiming unused object and heap thrashing. how to use object pool pattern in android to improve performance of the application.
What is the difference between Front Controller Design Pattern and MVC Design Pattern
In my application all the request are first directed to generic controller servlet and then more specific controllers are being called. We are also using POJOs and JSP as the Model and View respectively. So should i call this front controller or an MVC design pattern.
How to access a method in the context through unit of work?
If I have the following Context :
public partial class HRMainDataCTX : DbContext
{
public HRMainDataCTX()
: base("name=HRMainDataCTX")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
//DbSets
public virtual int SEARCHEMPLOYEE(Nullable<decimal> p_EMP_NUM, string p_EMP_NAME)
{
var p_EMP_NUMParameter = p_EMP_NUM.HasValue ?
new ObjectParameter("P_EMP_NUM", p_EMP_NUM) :
new ObjectParameter("P_EMP_NUM", typeof(decimal));
var p_EMP_NAMEParameter = p_EMP_NAME != null ?
new ObjectParameter("P_EMP_NAME", p_EMP_NAME) :
new ObjectParameter("P_EMP_NAME", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("SEARCHEMPLOYEE", p_EMP_NUMParameter, p_EMP_NAMEParameter);
}
}
Now i implement Unit of work like this :
public class HRCTX : IDisposable
{
private readonly HRMainDataCTX _context;
public HRCTX()
{
_context = new HRMainDataCTX();
}
public HRCTX(HRMainDataCTX context)
{
_context = context;
}
public int Save()
{
return _context.SaveChanges();
}
public HRMainDataCTX Context
{
get { return _context; }
}
public void Dispose()
{
_context.Dispose();
}
}
I don't know how to access the method (stored procedure) SEARCHEMPLOYEE
through UOW in my code behind.
Is this Adapter or Facade?
So I've convinced myself I was using Facade, but after taking a look at the Adapter pattern, I feel confused right now. So basically, I have 3 classes involved, a ServerCommunication, an Anti-Spam Server and a Normal Server. Both servers use the ServerCommunication to start working. I created a class where I created a method to start one server type or another, plus I created some other method like "printOnlineUsers" where I get the list of clients connected from the server and print them , and some other methods. It's basically a class where you can manage a Server easily. I don't know if these details are enough, so here's a piece of my code.
public class EzServer {
private ServerComm serverComm = new NetServerComm();
private Server server = Server.getInstance();
private ServerComm decoratedServerComm = new TransparentSpamFilter(serverComm);
public void startNormalServer() {
server.start(serverComm);
JOptionPane.showMessageDialog(null, "Normal server");
serverComm.start();
}
public void startAntiSpamServer() {
JOptionPane.showMessageDialog(null, "Anti spam server");
server.start(decoratedServerComm);
decoratedServerComm.start();
}
public int getTotalOnlineUsers() {
return Server.getInstance().getConnectedClients().size();
}
public boolean isClientOnline(String nickname) {
return Server.getInstance().getConnectedClientByNickname(nickname) != null;
}
public void disconnectClient(String nickname) {
serverComm.disconnectClient(nickname);
}
public void printOnlineUsers() {
List<Client> list = Server.getInstance().getConnectedClients();
if (list != null && !list.isEmpty()) {
System.out.println("Online users:");
for (Client client : list) {
System.out.println(client.getNickname());
}
} else {
System.out.println("No online users");
}
}
}
Abstract Factory with two diferent model DB's
I'm using a Abstract FactoryPattern with two diferent DB Models (Oracle and DB2), according with this pattern I have to implement all of the methods for each factoryDAo, but I don't want to have the methods of Oracle in my FactoryDao DB2, because the DB model it's different.
Now the question is, what is the best practice in this case, how I have to implement this pattern to isolate both models?
FACTORY
public abstract class DAOFactory {
public static final int ORACLE = 1;
public static final int DB2 = 2;
public abstract ApplicationDAO getApplicationDAO() throws HibernateException;
.
.
public static DAOFactory getDAOFactory(int factory) {
switch (factory) {
case ORACLE:
return new OracleFactoryDao();
case DB2:
return new Db2FactoryDao();
}
return null;
}
FACTORYDAO
public class OracleFactoryDao extends DAOFactory {
public ApplicationDAOImpl getApplicationDAO() {
return new ApplicationDAOImpl();
}
..}
public class DB2FactoryDao extends DAOFactory {
public ApplicationDAOImpl getApplicationDAO() {
return new ApplicationDAOImpl();
}..}
Javascript Modules Creations
I am trying to develop a logical component that will be used in addition with other components that i plan to create. One thing i just don't get. I am sure there is a better way of doing this but i can't think of one.
var AwesomeModule = function (selector, options) {
selector = document.querySelector(selector);
options = options ? options : {};
// Create Defaults
options.name = name ? name : '';
options.type = type ? type : '';
options.style = style ? style : '';
options.color = color ? color : '';
}
Is there a way to extend some of this 'default settings' without doing this pattern of checking if an item exists and if no evaluated it to an empty specific type..ex: string, object, array?
Any indications about this is highly valued
lundi 28 mars 2016
How can I use sed to add search pattern in multi-line string after?
I have this text in file:
<TAG-ONE> multi
line
text
<TAG-TWO> multi
line
text
I want get it:
<TAG-ONE> multi
line
text
</TAG-ONE>
<TAG-TWO> multi
line
text
</TAG-TWO>
Please help me end this pattern:
sed '/^<[A-Z-]*>/,/^</{s/^<\([A-Z-]*\)>/&\n\1/}'
Expose Methods in Properties as Single Class
I needed to break up a WCF service contract that had a massive interface and clientbase class into smaller classes. All of the smaller classes are similar but have different operation contracts. I want to be able to expose the operation contract methods in all the new sub-classes as a single class for backwards compatibility. Ideally it would look something like this:
public class MainClient {
public MainClient() {
Sub1 = new Sub1Client();
Sub2 = new Sub2Client();
}
public static Sub1Client Sub1;
public static Sub2Client Sub2;
}
I would then want to be able to call methods from Sub1
and Sub2
as if those methods were defined in MainClient
. So instead of calling (new MainClient()).Sub1.Method1()
I would call (new MainClient()).Method1()
where Method1
still exists in the Sub1Client
class.
Is this possible?
c# method looks very redundant what can i do to fix it design pattern , method?
I have this method in C# that looks like I should really refactor it . Should I use a design pattern ? Too much repetition is what I see NOW and especially as MORE conditional if statements get added
Change to a method?
public void CreateOrUpdateReportDefinition(ReportGroupSubReport reportGroupSubReport, bool isNew, int report)
{
if (report == 1)
{
var entity = _envyUnitOfWork.ReportDefinitions.GetById(reportGroupSubReport.Id) ?? new ReportDefinition();
if (isNew)
entity.SetNew();
_envyUnitOfWork.ReportDefinitions.InsertOrUpdate(entity, true);
}
else if (report == 2)
{
var entity = _envyUnitOfWork.TraxReports.GetById(reportGroupSubReport.Id) ?? new TraxReport();
if (isNew)
entity.SetNew();
_envyUnitOfWork.TraxReports.InsertOrUpdate(entity, true);
}
Mapper.Map(reportGroupSubReport, entity);
_envyUnitOfWork.Commit();
}
Match strings based on placeholder only C#/SQL [on hold]
Have two strings and want to compare and match based on only the placeholder texts. When I compare String 1 & String 2 result as true and String 1 & string 3 as false.
String 1 = {0} successfully {1}
String 2 = {1} Com êxito {0}
String 3 = {1} Com êxito {2}
RegEx, C# or SQL is preferred.
Book for advanced CUDA developers
Can someone suggest a good book in cuda. I already read the book "CUDA by Examples".
I'm looking for some topics like Design patterns, Data structure, special Technics and tricks.
Using MVC style, where is the best place to call my query functions?
I am wondering about best practices here.
MVC (Model - View - Controller) patterns involve separating components of your program that model the data, manipulate those models, and display those results to the user (usually through the UI) in some way.
What about a function that takes the model data and inserts it into a database? For example I have an object called a GameBoard, and I also want the ability to insert the state of this board into the SQL database for storage / historical purposes. I have a class that holds all my query functions. I am not asking where to store the query calls themselves -- again those are all encapsulated in one class.
But where would I call these functions from? Would this sort of functionality make the most sense to make it as a method of GameBoard? Or should it be part of the controller classes?
Efficient design pattern to perform a one-to-one mappings from a type hierarchy to set of values
I would like to call an external vendor's api method on types in my local library. The vendor's method takes a setting in the form of a string which can take on several values, say "Cat"
and "Dog"
. I am performing the mapping from my type to the vendor's setting string thus:
public class Program {
interface LocalType {}
static class LocalCat implements LocalType {}
static class LocalDog implements LocalType {}
// Calls some API to get the animal's sound
interface AnimalSounds {
void playSound(LocalType t);
}
// Vendor-specific implementation
static class VendorSounds implements AnimalSounds{
private static VendorAPI api = new VendorAPI();
@Override public void playSound(LocalType t) {
// Map local type to vendor setting
if (t instanceof LocalCat)
api.vendorMethod("Cat");
else if (t instanceof LocalDog)
api.vendorMethod("Dog");
}
}
// API defined externally by vendor (reproduced here for illustration)
static class VendorAPI {
static void vendorMethod(String type) {
// Do something
}
}
public static void main(String[] args) {
AnimalSounds s = new VendorSounds(); // Choose vendor
s.playSound(new LocalCat()); // For example
}
}
Here "Cat"
and "Dog"
are vendor-specific settings; I may later change to a French vendor where these two are "Chat"
and "Chien"
, respectively. So to avoid adding vendor-specific information to the LocalType
hierarchy which would then have to change each time I change vendors, I hid this mapping in a sort of adapter AnimalSounds
(I added VendorSounds
as an example for one vendor).
But the cascade of instanceof
smells like poor design to me, is there perhaps a more elegant way of accomplishing this which I have overlooked?
If In Proxy Pattern we have interface instead of real Subject in Proxy class is it equivalent to Decorator Pattern
Proxy pattern delegates the request to the Real subject after doing some additional processing like applying checks if to process the request.
It has class diagram as below
Proxy class has a direct reference to the concrete Subject.
Decorator Pattern enriches the behavior of the component [like proxy it also does some additional processing and delegates the operation to the real component]. The class diagram of this pattern is similar to Proxy pattern with only difference being it has the reference to the interface of the component.
Having concrete real subject in Proxy class makes it difficult for unit testing as Classes should only be dependent upon interfaces and not the implementations. My Question is if Proxy pattern also has the reference to the interface exposed by the Real subject then will it be equivalent to the Decorator pattern. In such a case the class diagram of the proxy pattern will also become as below
How I can use singleton pattern with abstract factory pattern?
I have to use singleton with combine abstract factory. How I can do that in java
Regular expression that matches "{$" AND NOT matches "\{$"
I am working on a project with lexical analysis and basically I have to generate tokens that are text and that are not text.
- Tokens that are text are considered all characters until the
"{$"
sequence. - Tokens that are not text are considered all characters inside the
"{$"
and"$}"
sequences.
Note that the "{$"
character sequence can be escaped by writing "\{$"
so this also becomes a part of text.
My job is to read a String of text, and for that I am using Regular expressions.
I am using the Java Scanner and Pattern classes and this is my work so far:
String text = "This is \\{$ just text$}\nThis is {$not_text$}."
Scanner sc = new Scanner(text);
Pattern textPattern = Pattern.compile("{\\$"); // insert working regex here
sc.useDelimiter(textPattern);
System.out.println(sc.next());
This is what should be printed out:
This is \{$ just text$}
This is
How do I make a regex for the following logical statement:
match "{$" AND NOT match "\{$"
Singleton design pattern, static access non static?
I think to a common Singleton Design Pattern:
public class Singleton{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null)
instance=new Singleton();
return instance;
}
}
as far as I know, costructors are NON static methods because they can use the context reference "this" (which is forbidden in static contexts). On the other hand, static members can access only static members.
So how is it possible that static member getInstance() is accessing the non static member constructor?
Difference between Factory pattern and Inversion of control?
Factory pattern and Dependency Injection both are creational design patterns and in both the patterns we are delegating the responsibility of object creation to some seperate class. Then what is the exact difference between the two and what is the exact scenario where the implementation difference will be effective and markable ?
dimanche 27 mars 2016
i am trying to create a number pattern in java. There is a slight error in the condition of the second inner for loop. I am not able to rectify it
the pattern is supposed to look like this:
1234
2345
3456
4567
i have divided it into two seperate triangles:
1234
234 5
34 56
4 567
i have done this much.Please help.
public class pattern
{
void main(int n)
{
for(int i =1;i <= n; i++)
{
for(int j = i;j<=n;j++)
{System.out.print(j);}
for(int j = n+1;j<=(i*2)-1;j++)
{System.out.print(j);}
System.out.println();
}
}
}
Load data aysnchronously using Django REST
I am having a REST service which returns a list of players and their scores. The calculation of score for each user in the list is heavy as it is being done for each request and it involves database interactions. How can I optimize this?
The options which I can think of is -
-
Cache the score calculation and invalidate cache at certain intervals.
- How to do this in django-rest-framework elegantly?
- The cache need be invalidated frequently, maximum 5 mins. (This factor tells me that caching will be too heavy and not so effective)
-
Load the list of users and send their scores asynchronously.
- Where will handled by Server & what will be on Client?
- Will it be like 1 request to load list of 100 users and then 100 requests to get their corresponding scores?
Or you can tell me some other better pattern to follow?
Get a specific word after pattern
I want to take the word 'desired' from the example below. How would I do that in python. Like what to do in the case of single line comments as shown below. I have tried something like print text.split(" ")[1] but it will only work in the case where there are no single line comments.
text = /* */
The desired {word}
/* */
Difference between architectural styles and architectural patterns
what is the difference between architectural styles and patterns in software architecture?
Are they considered the same?
Thanx
Designing a class that does not need to maintain state
I am trying to make an application that would need to extract the major colours of an image. So I made a class that has a few functions which are used to identify the major of colours(Like generate histogram, flatten image, make clusters of colors etc.). These functions are unrelated to each other, but together they achieve a certain functionality. But I am not sure how to actually design the class. Right now I am taking an image(or path to image) as an input parameter in Constructor/SetImage function. But I figured that attaching this image to the state of class is of no use. The basic functionality is just to feed it an image and get something in return. I felt it might be better if i wrote just a function, but I would like to connect the other functions with the main used function somehow as well. I thought maybe i should write all of them as static, but I am not sure, if that would be the correct way to do it.
I am not sure if this case falls into a design pattern(which i have read, or maybe i couldn't think a way to pout this into that). Not sure what the best convention would be.
What I want to do is, Initialize the class, and then call a function and get the results. I could surely write something simple as that, explicitly passing arguments, and stuff. But I want to make sure I don't miss out knowing the best practices and conventions. I am currently writing the code in Python, but I don't want a python centric solution(like maybe do something by implementing the call method or something.)
Heres the code I have right now.
class colorIdentifier(object):
def __init__(self,**kwargs):
self.img = None
self.hist = None
def setImg(self, img):
if(type(img) is str):
self.img = cv2.imread(img)
self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
else:
self.img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h, w, _ = self.img.shape
w_new = int(100 * w / max(w, h) )
h_new = int(100 * h / max(w, h) )
self.img = cv2.resize(self.img, (w_new, h_new))
def flatten(self,img):
image_array = self.img.reshape((self.img.shape[0] * self.img.shape[1], 3))
# Clusters the pixels
self.clt = KMeans(n_clusters = 3)
self.clt.fit(image_array)
def getClusters(self):
clt = self.clt
# Finds how many pixels are in each cluster
self.hist = self.__centroid_histogram(clt)
# Sort the clusters according to how many pixel they have
zipped = zip (self.hist, clt.cluster_centers_)
zipped.sort(reverse=True, key=lambda x : x[0])
self.hist, clt.cluster_centers = zip(*zipped)
def __centroid_histogram__(self,clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins = numLabels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
counting the times a word that starts with an A or a appears from a file
Ok so I have this program and its supposed to read a file, "englishsorted.txt", and count the number of times a word that begins with an "A" or "a" occurs. I'm supposed to use a pattern object. I am not really sure what I'm missing/have wrong. I appreciate the help.
import sys
import re
count = 0
x = open("englishsorted.txt", "r")
while 1:
pattern = x.readline()
if pattern == re.compile(r'^[A,a].'): #regex that finds words starting with an A or a
count = count + 1
x.close()
print count
Elegant pattern for scoped_lock to access resource?
I have objects in containers that are access-controlled with mutexes. I often do something like:
rsrc *r;
{
scoped_lock l(mtx);
r = container.pop( );
}
// ... use r
(I use scoped_lock to ensure clean up after exceptions, etc.) However, I don't like the { ... } block that's not part of an explicit control structure (it's only there to make a scope for the scoped_lock) and I don't like the null initialization of r followed by (probable but not certain) assignment in the { ... } block.
I can do something like this:
inline rsrc *locked_pop( mutex &mtx, container &c ) { scoped_lock l(mtx); return c.pop( ); }
and then
rsrc *r = locked_pop( mtx, container );
which is OK, but I have situations where I need to get several items from same (or different) container, under the same lock.
Do you know of an elegant, general way of doing this? (This is not specifically a Boost question, but I'm using those libraries so a Boost-ism would be fine.)
cab booking system design pattern [on hold]
Which design pattern in java should be used in Cab booking system?
I have gone through multiple design patterns but cannot figuree out which one suits the best to this problem.
Can I Write C# in a Functional Way
I am working on a project with a few other developers. We are ready to start building the component that handles the business logic. We are all skilled in C#. Functional programming for business logic and F# has been brought up by the client multiple times. I am failing to connect the dots. I understand using functional concepts like this. My question is: Is functional programming simply a paradigm shift, or should we actually start using another language like F#?
Cab booking system java code
I need help in writing a Cab booking system java code for an interview, can you all suggest what design pattern to be used?
Please post code if possible
- There are n number of taxi’s. For simplicity, assume 4. But it should work for any number of taxi’s.
- The are 6 points(A,B,C,D,E,F)
- All the points are in a straight line, and each point is 15kms away from the adjacent points.
- It takes 60 mins to travel from one point to another
- Each taxi charges Rs.100 minimum for the first 5 kilometers and Rs.10 for the subsequent kilometers.
- For simplicity, time can be entered as absolute time. Eg: 9hrs, 15hrs etc.
- All taxi’s are initially stationed at A.
- When a customer books a Taxi, a free taxi at that point is allocated
- If no free taxi is available at that point, a free taxi at the nearest point is allocated.
- If two taxi’s are free at the same point, one with lower earning is allocated
- Note that the taxi only charges the customer from the pickup point to the drop point. Not the distance it travels from an adjacent point to pickup the customer.
- If no taxi is free at that time, booking is rejected
-
samedi 26 mars 2016
Pattern for overriding db records
I'm looking for a pattern or code example where a user can enter their own records, that override the default records. For example a Holiday table.
Defaults records may be:
HolidayName Holiday Date CompanyId
----------- ------------ ---------
New Year 01-Jan-2016 NULL
Day After 02-Jan-2016 NULL
And after the user adds their own holidays (for CompanyId "1234"):
HolidayName Holiday Date CompanyId
----------- ------------ ---------
New Year 01-Jan-2016 NULL
Day After 02-Jan-2016 NULL
Another Name 01-Jan-2016 1234
My Holiday 03-Jan-2016 1234
Joes Holiday 04-Jan-2016 5678
How can I retrive a list of holidays that are a compinbation of: 1. the default Holidays (where CompanyId = NULL), or 2. the overridden holidays (with the same date),
3. And includes additional holidays entered by the user (by CompanyID). Like this for companyId=1234:
HolidayName Holiday Date CompanyId
----------- ------------ ---------
Another Name 01-Jan-2016 1234
Day After 02-Jan-2016 NULL
My Holiday 03-Jan-2016 1234
Not sure if this could done in either a SQL view, Query or C# code.
How to communicate data from children workers to parent class?
I'm writing an application in C# that needs to spawn worker threads that will retrieve data from various places (databases, ftp sites, websites, text files, queues etc. etc.) and make the data available to another consuming thread.
I have the application written and it's working nicely.
However, I want to restructure it so that it's more testable and to attempt to follow SRP. Right now, almost all of the work is done in one class.
Currently, my main class is loading configuration files (one for each type of data retriever - database, web, text file, ftp etc.) and starting a timer per type to check for work. If there is work to do, the background thread does the work and populates a ConcurrentQueue which is then read by the main thread.
What's the best way to restructure to code to meet my needs? How do I best communicate the data and performance metrics back from the workers? What are the best design patterns to use in this scenario?
Instance Methods vs. Class methods For a Helper Class - Ruby, Rails
I am working on a rake task
which creates new records in local db based on a query submitted to an external db (MS SQL
). Connection, querying and record creating happens in a helper I created called ExternalDatabaseConnector
. Rake tasks simply calls methods and operates as controller
of sort.
My question is whether the helper class methods (I have establish_connection
, execute_query
, create_hash
and store_records
) should be called on self
(i.e. be class methods) or each be called on an instance of my helper?
I am thinking that there will only be one connection and the rake task will only fire once per its schedule, and there is no need to create separate instances of my helper class?
How to audit and versioning over entity framework 6?
I'm New to The Entity Framework as ORM
.
I want to ask about robust solution for Auditing and Versioning
using EF
.
THE REQUIREMENTS:
- Usable with DB First and Code First
- Can Audit (INSERT,UPDATE,DELETE) including (transactions).
- can audit on the m-m relationships .
I search and find some solutions but find many drawbacks like need to implement soft-deletes
.
Convert if else to Pattern
I am using Laravel to build a system, this system is very complex and it contains too many if else, I want to change and clean up the code to be easier to maintain.
I have something like this
if(A)
{
call_a();
}
else
{
if(B)
{
call_a();
}
else
{
if()
{
call_b();
}
else
{
if(C)
{
call_a();
}
else
{
call_b();
}
}
}
}
of course its more and more complex.
Any help ? THanks
Singleton class object referenced by null
I have a question, where i have a singleton class and it's instance is referenced in many places in my project. Now the question is what happens at one the place the instance is assigned with null reference. Will it point to null reference rest of the places, If this is the case how can i avoid it?
public enum Test {
INSTANCE;
public void fun(){
System.out.println("hello");
}
}
public class Main {
public static void main(String[] args) {
Test test = Test.INSTANCE;
test.fun();
test = null;
test.fun();
}
}
OOMD - Is there a need of showing database connection in UML Class diagram? (A simple login diagram)
I want to design a class diagram of a simple login operation. Use case is:
- User enters id and pin
- System checks login info.
So, I decided to create a controller for the user (UserHandler
) and a user class (User
). UserHandler takes id and pin and checks that they are valid with a method ( isUserValid()
).
In my opinion, a class should not include all database records for only one of them. I mean there should not be a list of users to check whether login info is correct or not. This is a simple operation with just a requirement of connecting to database.
My question is how can I show that isUserValid()
method is connecting to the database? Is there a need of showing this connection?
Or should I create a userList
in UserHandler
and keep all the users in that list?
Any help will be very appriciated.
How can I avoid filling my JavaScript code with type-checking logic when using dependency injection?
I'm trying to employ SOLID principles learnt from strongly-typed languages in a Node.js application, and implement dependency injection through the constructor in my modules.
Without a compiler to help me, I've found myself impulsively writing type-checking and null-reference checking logic to make sure dependencies of the correct type are being passed in.
var _ = require('lodash');
var ExampleModule = function(dependencies) {
var app, express, http;
if(_.isUndefined(dependencies) || typeof dependencies !== 'object') {
throw new ReferenceError('No dependencies object passed to the constructor. Actually passed: ' + typeof dependencies);
}
if(_.isUndefined(dependencies.express)) {
throw new ReferenceError('The express module must be passed as the \'express\' property in the constructor.');
} else {
express = dependencies.express;
}
// Tempted to add a type check for dependencies.express here
if(_.isUndefined(dependencies.http)) {
throw new ReferenceError('The node http module must be passed as the \'http\' property in the constructor.');
} else {
http = dependencies.http;
}
// Tempted to add a type check for dependencies.http here
};
module.exports = ExampleModule;
This feels fundamentally wrong for two reasons
- Constructors filled with many conditional statements; likely to increase in size as more dependencies are needed.
- Many extra unit tests are written to check the type-checks and null-reference checks are working
I don't want to spend half my time maintaining type-checking logic, but I also don't want to spend half my time debugging errors when the wrong type of a dependency is passed in.
What design pattern am I missing that would solve this problem?
vendredi 25 mars 2016
Design Practices, Adding field to model or querying global object for data in a factory
So here is the situation, Say I have a class called factory, Factory is used for building cardViews to display to the user. In a Certain number of cases(currently small), The I want the card not to be dismissible(aka have an x at the top) or have any buttons on it that in other cases have functionality. Now say we have some class WholeDataProvider, and data provider has an object in it called currentEnvironment, with a field called cardEditable. Now the card factory currently does not know about WholeDataProvider, currentEnvironment..etc. Now this object is accessible in this case its just not currently imported. The factory method takes in a data model lets call it cardDataModel which tells the factory information on what card to layout and return. Now my Idea was to add a field to this model thats something along the lines of boolean drawInteractivity. Now the place where the cardDataModel is created already has the class WholeDataProvider imported so I chose to add the field to the card and not try and add dependencies in the creator class.
Now although this works, I am being told to add the call to WholeDataModel the factory class.
my question more or less is can anyone give me some rules or guidance or information...etc regarding the usage of data models in factory methods or an explanation as to why moving the call would be a better idea. to me it would seem that the data model should provide everything the factory needs to know.
Thanks for any comments or info.
Identifying best pattern for exposing JS utility functions
I'm trying to build a JS file for our project which will expose some generic utility functions. I've used the following two patterns before but not convinced with them entirely.
Pattern 1
var objUtils = {
foo: function(){
//code
},
bar: function(){
//code
//foo can't be called
}
}
The problem with the above pattern is that I can't invoke cross-invoke the functions.
Pattern 2
var objUtils = (function(){
var foo = function(){
},
bar = function(){
}
return{
foo : foo,
bar : bar
}
})();
The problem with the above pattern is that every time I add a new function I've to make sure that I add it to the return block to make it exposed, which I feel is kind of a redundant work.
Any thoughts?
How this "container Design pattern" called?
While creating my app. architecture I faced the need of one structure, that will be described below. I'm pretty sure, that there is a well known design pattern with the same functionality, because I think that problem, for which I develop it is really common. I write my own implementation of this, but I always try to use "build in language" implementations of patterns, so - please help me to "named" this construction.
The idea is close to reader-writer pattern. We have a "container" in which we can add Objects by the key (). And also we can get this objects by keys, removing it from container. So, the implemented class should have two methods:
void putObject(Key key, Object object);
Object getObject(Key key); // remove <Key,Object> from container.
The next is most interesting. This container should work in multi-threading environment as follows:
- if there is no object associated with key, while calling get(Key key) method the caller thread should WAIT for the object in this contaier.
- When another thread will call putObject(Key key, Object object) method it should check if there is some thread that wait exactly for this object, and if it is - then signal and wake up the thread that waits.
I think that it is common structure, does it have "official" name? Thank you.
PS my Java implementation of this pattern:
private static interface BlackBox {
public void addObject(IdObject object);
public IdObject getObject(ObjectId id);
}
private static class BlackBoxImpl implements BlackBox {
private final Lock conditionLock = new ReentrantLock();
private final SavedObjects savedObjects;
private final WaitingConditions waitingConditions;
public BlackBoxImpl() {
this.savedObjects = new SavedObjects();
this.waitingConditions = new WaitingConditions();
}
@Override
public void addObject(IdObject object) {
savedObjects.putObject(object);
if (waitingConditions.contains(object.getId())) {
Condition waitCondition = waitingConditions.getCondition(object.getId());
conditionLock.lock();
waitCondition.signal();
conditionLock.unlock();
}
}
@Override
public IdObject getObject(ObjectId id) {
if (savedObjects.containsId(id)) {
return savedObjects.get(id);
} else {
conditionLock.lock();
Condition waitCondition = conditionLock.newCondition();
waitingConditions.putCondition(id, waitCondition);
waitCondition.awaitUninterruptibly();
conditionLock.unlock();
return savedObjects.get(id);
}
}
}
private static class SavedObjects {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Map<ObjectId, IdObject> savedObjects;
public SavedObjects() {
this.savedObjects = new HashMap<ObjectId, IdObject>(20);
}
public boolean containsId(ObjectId id) {
lock.readLock().lock();
try {
return savedObjects.containsKey(id);
} finally {
lock.readLock().unlock();
}
}
public void putObject(IdObject object) {
lock.writeLock().lock();
try {
savedObjects.put(object.getId(), object);
} finally {
lock.writeLock().unlock();
}
}
public IdObject get(ObjectId id) {
lock.writeLock().lock();
try {
return savedObjects.remove(id);
} finally {
lock.writeLock().unlock();
}
}
}
private static class WaitingConditions {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Map<ObjectId, Condition> waitingForSuchObjects;
public WaitingConditions() {
this.waitingForSuchObjects = new HashMap<ObjectId, Condition>(20);
}
public void putCondition(ObjectId id, Condition condition) {
lock.writeLock().lock();
try {
waitingForSuchObjects.put(id, condition);
} finally {
lock.writeLock().unlock();
}
}
public Condition getCondition(ObjectId id) {
lock.writeLock().lock();
try {
return waitingForSuchObjects.remove(id);
} finally {
lock.writeLock().unlock();
}
}
public boolean contains(ObjectId id) {
lock.readLock().lock();
try {
return waitingForSuchObjects.containsKey(id);
} finally {
lock.readLock().unlock();
}
}
}
private static interface IdObject {
public ObjectId getId();
}
private static class IdObjectImpl implements IdObject {
protected final ObjectId id;
public IdObjectImpl(ObjectId id) {
this.id = id;
}
@Override
public ObjectId getId() {
return id;
}
}
private static interface ObjectId {
}
private static class ObjectIdImpl implements ObjectId {
}
Cloud Design Patterns - best examples and best practices
I have start to learn Cloud Design Patterns and actually i can't find good examples explained and best practices. Can you give some good links about learning these patterns and some information about starting fast from zero. At the moment i am reading this book: http://ift.tt/1UQu6Tq.
Thanks in advance
Eliminate if-else from while-loop
I have two class:
class A:
b = B()
function doSomething():
while True:
b.doSomething()
class B:
counter = 0
function doSomething():
if counter < 10:
performMethod1()
else:
performMethod2()
counter += 1
function performMethod1(): ...
function performMethod2(): ...
I feel this code is bad, because I know that B.performMethod2() is going to be performed much more times than B.performMethod1(), but the if-else (if counter < 10) is going to be checked every time I go inside B.doSomething().
Additionally, I don't want to break the while-loop of class A, because I want to hide the implementation details of class B from A.doSomething().
Is there any good way to eliminate the if-else of B.doSomething()? Thank you.
jeudi 24 mars 2016
Multiple Visitors on related classes
I'm simplifying things to point out my basic design problem.
I have an hierarchy like this:
R <-- interface
/ \
/ \
/ \
BR RR <-- abstract classes
/ | \ / | \
/ | \ / | \
BRA BRB BRC RRA RRB RRC <-- classes
where BRA
, BRB
, BRC
, RRA
, RRB
and RRC
are classes that need to be visited.
I also have two visitor classes, who don't share any common ancestor class (for now). So, finally, the code is structured like this:
public interface R {
/* . . . */
}
public abstract class BR implements R {
/* . . . */
public abstract void accept(VisitorBR vbr);
}
public abstract class RR implements R {
/* . . . */
public abstract void accept(VisitorRR vrr);
}
public class BRA extends BR {
/* . . . */
public void accept(VisitorBR vbr) { vbr.visit(this); }
}
public class BRB extends BR {
/* . . . */
public void accept(VisitorBR vbr) { vbr.visit(this); }
}
public class BRC extends BR {
/* . . . */
public void accept(VisitorBR vbr) { vbr.visit(this); }
}
public class RRA extends RR {
/* . . . */
public void accept(VisitorRR vrr) { vrr.visit(this); }
}
public class RRB extends RR {
/* . . . */
public void accept(VisitorRR vrr) { vrr.visit(this); }
}
public class RRC extends RR {
/* . . . */
public void accept(VisitorRR vrr) { vrr.visit(this); }
}
and
public class VisitorBR {
/* . . . */
public void visit(BRA r) { /* . . . */ }
public void visit(BRB r) { /* . . . */ }
public void visit(BRC r) { /* . . . */ }
}
public class VisitorRR {
/* . . . */
public void visit(RRA r) { /* . . . */ }
public void visit(RRB r) { /* . . . */ }
public void visit(RRC r) { /* . . . */ }
}
The client class has a BlockingQueue<R>
, and one reference to an object of each visitor class, and needs to handle all elements of the queue using the most suitable visitor. Looks like this:
public class Client implements Runnable {
private VisitorBR vbr;
private VisitorRR vrr;
private BlockingQueue<R> q;
/* . . . */
@Override
void run() {
for (;;) {
R r = q.take();
/*** Somehow handle r with the most suitable visitor, ***/
/*** based on whether it's descendant of BR or RR. ***/
}
}
}
What would be the most elegant solution for this? By the way, in any case, the visitors must not be nested classes.
My workaround is to define public static final
enum fields in abstract classes BR
and RR
to distinguish them, and use an if
block, something like this:
@Override
void run() {
for (;;) {
R r = q.take();
if (r.getType() == BR)
((BR) r).accept(vbr);
else // if (r.getType() == RR)
((RR) r).accept(vrr)
}
}
But there has to be a more elegant solution to combine two visitor classes than this.